类的装饰器应用
class Typed:
def __init__(self,key,expected_type):
self.key = key
self.expected_type = expected_type
def __get__(self, instance, owner):
print('get方法--%s--%s' %(instance,owner))
return instance.__dict__[self.key]
def __set__(self, instance, value):
print('set方法-%s---%s'%(instance,value))
if not isinstance(value,self.expected_type):
# print('你传入的类型不是字符串,请修改错误')
# return
raise TypeError('%s传入的类型不是%s'%(self.key,self.expected_type))
instance.__dict__[self.key]=value
def __delete__(self, instance):
print('delete')
instance.__dict__.pop(self.key)
#类的装饰器应用
def deco(**kwargs):
def wrapper(obj):
for key,val in kwargs.items():
setattr(obj,key,Typed(key,val))
return obj
return wrapper
#name属性被数据描述符代理
@deco(name=str)
class People:
def __init__(self,name,age,salary):
self.name = name
self.age = age
self.salary = salary
p1 = People('999',18,100)
print(p1.__dict__)
#类属性>数据描述符>实例属性>费数据描述符>不存在
# p1.name = 'xiaorong'
# print(p1.name)
# print(p1.__dict__)
# del p1.name
# print(p1.__dict__)
# xiaoming
# {'name': 'xiaoming', 'age': 18, 'salary': 100}
# delete
# {'age': 18, 'salary': 100}
自制property
#装饰器
class Lazy_property:
def __init__(self,func):
self.func = func
print('----------',func)
def __get__(self, instance, owner):
print('get')
print('1111111111',instance,owner)
return self.func(instance)
class Room:
def __init__(self,name,width,height):
self.name = name
self.width = width
self.height = height
@Lazy_property #are = Lazy_property(are)
def are(self):
return self.width*self.height
r1 =Room('厨房',100,100)
print(r1.are)