# class Student(object):
# def get_seocre(self):
# return self._score
# def set_11(self,value):
# if not isinstance(value,int):
# raise ValueError('error')
# if value<0 or value>100:
# raise ValueError('error0 and 100')
# self._score=value
#
# s=Student()
# s.set_11(60)
# print (s.get_seocre())
class Student(object):
@property
def score(self):
return self._score
@score.setter
def score(self, value):
if not isinstance(value, int):
raise ValueError('score must be an integer!')
if value < 0 or value > 100:
raise ValueError('score must between 0 ~ 100!')
self._score = value
s=Student()
s.score=60
print(s.score)
class F(object):
def __getitem__(self, item):
if isinstance(item,int):
a,b=1,1
for x in range(item):
a,b=b,a+b
return a
if isinstance(item,slice):
start=item.start
stop=item.stop
if start is None:
start=0
a,b=1,1
L=[]
for x in range(stop):
if x>=start:
L.append(a)
a,b=b,a+b
return L
f=F()
print (f[0:5])
print(f[:10])
print (f[:10:2])
from enum import Enum,unique
Month=Enum('Month',('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'))
for name,member in Month.__members__.items():
print (name,'=>',member,',',member.value)
#value属性则是自动赋给成员的int常量,默认从1开始计数。
@unique#@unique装饰器可以帮助我们检查保证没有重复值。
class Weekday(Enum):
Sum=0
Mon=1
Tue=2
Wed=3
Thu=4
Fir=5
Sat=6
day=Weekday.Sat
print (day)
print(Weekday['Tue'])
print (Weekday.Thu.value)
print (Weekday(1))
class ListMetaclass(type):
def __new__(cls, name,bases,attrs):
attrs['add']=lambda self,value:self.append(value)
return type.__new__(cls,name,bases,attrs)
class Mylist(list,metaclass=ListMetaclass):
pass
l=Mylist()
l.add(1)
print (l)
# l2=list()
# l2.add(1)
#ORM框架
class Field(object):
def __init__(self,name,colum):
self.name=name
self.colum=colum
def __str__(self):
return self.__class__.__name__,self.name
class StringField(Field):
def __init__(self,name):
super(StringField,self).__init__(name,'varchar(100)')
class InterFied(Field):
def __init__(self,name):
super(InterFied,self).__init__(name,'bigint')
class ModelMetaclass(type):
def __new__(cls,name,bases,attrs):
if name=='Model':
return type.__new__(cls,name,bases,attrs)
print(name)
mapping=dict()
for k,v in attrs.items():
if isinstance(v,Field):
print (k,v)
mapping[k]=v
for k in mapping.keys():
attrs.pop(k)
attrs['__mappings__']=mapping
attrs['__table__']=name
return type.__new__(cls,name,bases,attrs)
class Model(dict,metaclass=ModelMetaclass):
def __init__(self,**kw):
super(Model,self).__init__(**kw)
def __getattr__(self, item):
try:
return self[item]
except KeyError:
raise AttributeError(r"'Model' object has no attribute '%s'" % item)
def __setattr__(self, key, value):
self[key]=value
def save(self):
fields=[]
params=[]
args=[]
for k,v in self.__mappings__.items():
fields.append(v.name)
params.append('?')
args.append(getattr(self,k,None))
sql='insert into %s(%s) values (%s)'%(self.__table__,','.join(fields),','.join(params))
print (sql)
print (str(args))
class User(object):
id=InterFied('id')
name=StringField('username')
emial=StringField('email')
password=StringField('password')
u = User(id=12345, name='Michael', email='test@orm.org', password='my-pwd')
u.save()
# with open(r'a.txt','r')as f:
# for line in f.readlines():
# print (line.strip())
# f=open(r'aa.png','rb')
# print(f.read())
# f=open(r'a.txt','r',encoding='utf-8',errors='ignore')
# print (f.read())
from io import StringIO#StringIO操作的只能是str
f=StringIO()
f.write('hello')
f.write('')
f.write('world!')
print (f.getvalue())
f=StringIO('Hello!\nHi!\nGoodbye!')
while 1:
s=f.readline()
if s=='':
break
print(s.strip())
#二进制的话要使用就需要使用BytesIO。
from io import BytesIO
f=BytesIO()
f.write('中文'.encode('utf-8'))
print(f.getvalue())
s=b'\xe4\xb8\xad\xe6\x96\x87'
f=BytesIO(s)
print(f.read())
import sys,os
print(os.name)
print (os.uname())
import pickle
d = dict(name='Bob', age=20, score=88)
print (pickle.dumps(d))#pickle.dumps()方法把任意对象序列化成一个bytes
with open('dump.txt','wb') as f:
pickle.dump(d,f)
#pickle.load()方法从一个file-like Object中直接反序列化出对象。我们打开另一个Python命令行来反序列化刚才保存的对象:
with open(r'dump.txt','rb')as f:
d=pickle.load(f)
print (d)
import json
d = dict(name='Bob', age=20, score=88)
print(u'打印json:',json.dumps(d))#dumps()方法返回一个str,内容就是标准的JSON。类似的,dump()方法可以直接把JSON写入一个file-like Object。
json_str='{"name": "Bob", "age": 20, "score": 88}'
print(u'反json:',json.loads(json_str))#用loads()或者对应的load()方法,前者把JSON的字符串反序列化,后者从file-like Object中读取字符串并反序列化:
#自定义json序列
class Student(object):
def __init__(self,name,age,score):
self.name=name
self.age=age
self.score=score
s=Student('Bob',20,88)
# print(json.dumps(s))#不能直接进行json处理
#解决如下
def stu(s):
return {'name':s.name,
'age':s.age,
'score':s.score
}
print (json.dumps(s,default=stu))
#下次如果遇到一个Teacher类的实例,照样无法序列化为JSON。我们可以偷个懒,把任意class的实例变为dict:
print (json.dumps(s,default=lambda obj:obj.__dict__))
#反一个序列类的实例对象,loads()方法首先转换出一个dict对象,然后再传入即可,如下
def dict2(d):
return Student(d['name'],d['age'],d['score'])
print(json.loads(json_str,object_hook=dict2))