面向对象实用规则总结:
1,案例1
class List:
def __init__(self,li):
#必须是int
for i in li:
if not isinstance(i,int):
raise TypeError('必须是整形')
self.li = list(li)
def append(self,p_object):
#增加必须是str
if isinstance(p_object,str):
self.li.append(p_object)
else:
raise TypeError("必须是字符串")
@property
def mid(self):
#中间值
y = len(self.li)//2
return self.li[y]
def __str__(self):
return str(self.li)
def __getattr__(self, item):
#返回
return getattr(self.li,item)
2,案例2
import time
class User:
db_path='user.db'
def __init__(self,name):
self.name=name
@property
def db(self):
with open(self.db_path,'r') as read_file:
info=read_file.read()
return eval(info)
@db.setter
def db(self,value):
with open(self.db_path,'w') as write_file:
write_file.write(str(value))
write_file.flush()
@property
def search_locktime(self):
data = self.db
if data[self.name]['timeout'] < time.time():
return "没有被锁定"
else:
rest_time = data[self.name]['timeout']-time.time()
return "锁定时间%s"%rest_time
def login(self):
data=self.db
if data[self.name]['status']:
print('已经登录')
return True
if data[self.name]['timeout'] < time.time():
count=0
while count < 3:
passwd=input('password>>: ')
if not passwd:continue
if passwd == data[self.name]['password']:
data[self.name]['status']=True
data[self.name]['timeout']=0
self.db=data
break
count+=1
else:
data[self.name]['timeout']=time.time()+10
self.db=data
else:
print('账号已经锁定10秒')
def out(self):
data=self.db
if not data[self.name]['status']:
print("并没登录")
else:
data[self.name]['status'] = False
self.db = data
print('退出成功')
u2=User('alex')
u2.login()
print(u2.search_locktime)
u2.out()
知识点: 1,__getattr__ :能找到有就不执行,没找到执行
2,__delatrr__:删除的时候执行
3,__setattr__:赋值的时候执行
定制自己的数据类型:
1.继承的方式 :继承类,更改其中一个函数
2.授权的方式 :反射函数的其他方式,改变其中一个
补充:1,字符判定:
getattr,setattr,delattr,hasattr
2,判定类和父类:
isinstance,issubclass