python学习教程2

 1 常量定义(const需要用队形的方法创建)

class _const(object):
    class ConstError(TypeError):pass 
    def __setattr__(self, name, value): 
        if self.__dict__.has_key(name): 
            raise self.ConstError, "Can't rebind const (%s)" %name 
        self.__dict__[name]=value
    def __delattr__(self, name):
        if name in self.__dict__:
            raise self.ConstError, "Can't unbind const (%s)" %name
        raise NameError, name
import sys 
sys.modules[__name__] = _const()
2 数据类型
  • 整数型(int) 例:0、6、-2、2015、-203
  • 长整型(long) 例:56990l、-12694l、938476l
  • 浮点型(float) 例:7.5325、9.434、6.66
  • 布尔型(bool) 例:True、False
  • 复数型(complex) 例:6+4j、-5+12j、98+9j

 3 字符串

  ''单引号""双引号""""""三个引号(可以嵌套)

   4 转义符和换行符

print(complex(4,5))
coment = 'I\'m young'
print(coment)
print("young\npeople")
5自然字符和字符串重复

 自然字符串字面意思理解就是将字符串保留本身的格式,而不受转义的影响。

  字符串重复字面意思理解就是将字符串重复输出。

 实例代码:

comment=r'Our \nyoung'
print(comment)
description="Our \nyoung"
print(description)
three="Our young\n"*3
print(three)

6其它重要数据类型
# coding=utf-8
#列表
people=["刘一","陈二","张三","李四","王五","赵六","孙七","周八","吴九"]
print people[3]
#元组
names=("刘一","陈二","张三","李四","王五","赵六","孙七","周八","吴九")
print people[1]
#集合
xitems=set("1222234566666789")
xitems.add("x")
xitems.remove("8")
xitems.discard("8")
print xitems
yitems=set("1357")
#交集
print("交集:{0}".format(xitems&yitems)) #xitems&yitems = xitems.intersection(yitems)
#并集
print("并集:{0}".format(xitems|yitems)) #xitems|yitems = xitems.union(yitems)
#差集
print("差集:{0}".format(xitems-yitems)) #xitems-yitems = xitems.difference(yitems)
xitems.pop()
xitems.clear()
print("xitems集合被清空:{0}".format(xitems))
#字典
dictionary={'name':'toutou',"age":"26","sex":"male"}
print dictionary["name"]
#向字典中添加项目
dictionary['hobby']='cnblogs'
print dictionary["sex"]
print dictionary["hobby"]
数据类型

  7 对象系列化pickle模块(腌制)

# coding=utf-8
#pickle 模块化(腌制)
import pickle
#dumps(object)序列化
listx=["one","two","three"]
listb=pickle.dumps(listx)
print("dumps(object)序列化:{0}".format(listb))
#loads(string)反序列化
listz=pickle.loads(listb)
print("loads(string)反序列化:{0}".format(listz))
#demp(object,file),将对象序列化存储到文件
writeFile=file('test.pke','wb')
pickle.dump(listx,writeFile,True)
writeFile.close()
#load(object,file)将dump存储在文件里的数据反序列化
readFile=file('test.pke','rb')
listTemp=pickle.load(readFile)
print("#load(object,file)将dump存储在文件里的数据反序\n列化:{0}".format(listTemp))
readFile.close()
对象系列化
posted @ 2016-08-04 14:33  0胖嘟嘟二狗子0  阅读(166)  评论(0编辑  收藏  举报