1 class Type: 2 def __init__(self,key): 3 self.key = key 4 5 def __get__(self, instance, owner): 6 print('执行get方法') 7 return instance.__dict__[self.key] 8 9 def __set__(self, instance, value): 10 print('执行set方法') 11 instance.__dict__[self.key] = value 12 13 def __delete__(self, instance): 14 instance.__dict__.pop(self.key) 15 class Foo: 16 name = Type('name') 17 18 def __init__(self, name): 19 self.name = name 20 21 22 f1 = Foo('alex') 23 f1.name = 2 24 print(f1.__dict__) 25 print(f1.name) 26 输出: 27 执行set方法 28 执行set方法 29 {'name': 2} 30 执行get方法 31 2
可以对赋值加上条件判断
1 class Type: 2 def __init__(self,key): 3 self.key = key 4 5 def __get__(self, instance, owner): 6 print('执行get方法') 7 return instance.__dict__[self.key] 8 9 def __set__(self, instance, value): 10 print('执行set方法') 11 if not isinstance(value,str): 12 # print('你传入得不是字符串') 13 raise TypeError('你传入的不是字符串') 14 instance.__dict__[self.key] = value 15 16 def __delete__(self, instance): 17 instance.__dict__.pop(self.key) 18 class Foo: 19 name = Type('name') 20 21 def __init__(self, name): 22 self.name = name 23 24 25 f1 = Foo(3) 26 # f1.name = 2 27 # print(f1.__dict__) 28 # print(f1.name) 29 输出: 30 执行set方法 31 Traceback (most recent call last): 32 File "C:/Users/Administrator/Desktop/python/3月12日/描述符应用.py", line 25, in <module> 33 f1 = Foo(3) 34 File "C:/Users/Administrator/Desktop/python/3月12日/描述符应用.py", line 22, in __init__ 35 self.name = name 36 File "C:/Users/Administrator/Desktop/python/3月12日/描述符应用.py", line 13, in __set__ 37 raise TypeError('你传入的不是字符串') 38 TypeError: 你传入的不是字符串