标签:检测 通过 war elf item 描述 def let instance
1.使用描述符+类的装饰器
class Typed: def __init__(self,key,type): self.key=key self.type=type def __get__(self, instance, owner): return instance.__dict__[self.key] def __set__(self, instance, value): if not isinstance(value,self.type): raise TypeError("%s 不是%s" %(value,self.type)) instance.__dict__[self.key]=value def __delete__(self, instance): instance.__dict__.pop(self.key) def test(**kwargs): def test1(func): for i,o in kwargs.items(): setattr(func,i,Typed(i,o)) return func return test1 @test(name=str) class people: # name=Typed("name",str)#要设置类型 通过设置后可以不用这么麻烦可以直接修饰 # age=Typed("age",int) def __init__(self,name,age,salary): self.name=name self.age=age self.salary=salary s=people("rxy",123,123) print(s.name) print(people.__dict__)
2.使用property的补充
class People: def __init__(self,name): self.name=name #实例化就触发property @property def name(self): # return self.name #无限递归 print(‘get------>‘) return self.DouNiWan @name.setter def name(self,value): print(‘set------>‘) if not isinstance(value,str): raise TypeError(‘必须是字符串类型‘) self.DouNiWan=value @name.deleter def name(self): print(‘delete------>‘) del self.DouNiWan p1=People(‘alex‘) #self.name实际是存放到self.DouNiWan里 p1.name="1" print(p1.__dict__) print()
标签:检测 通过 war elf item 描述 def let instance
原文地址:https://www.cnblogs.com/rxybk/p/13284169.html