💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
>[success] # property 修饰的方法 ~~~ 1.第一种方法案例一,当继承setter或者deleter 修饰的方法子类使用super时候,里面两个参数填写子类的类 名,然后继承的 属性名字,后面接着对应的魔法方法,例如super(SubPerson, SubPerson).name.__set__(self, value) 2.如果直接不使用下面的第二个案例模式去定义,或是不像第一个全部重写,就会出现异常错误例如案例三 ~~~ >[danger] ##### 案例 ~~~ class Person: def __init__(self, name): self.name = name # Getter function @property def name(self): return self._name # Setter function @name.setter def name(self, value): if not isinstance(value, str): raise TypeError('Expected a string') self._name = value # Deleter function @name.deleter def name(self): raise AttributeError("Can't delete attribute") class SubPerson(Person): @property def name(self): print('Getting name') return super().name @name.setter def name(self, value): print('Setting name to', value) super(SubPerson, SubPerson).name.__set__(self, value) @name.deleter def name(self): print('Deleting name') super(SubPerson, SubPerson).name.__delete__(self) s = SubPerson('Guido') print(s.name) ~~~ >[danger] ##### 如果只想扩展其中的一个方法 ~~~ class SubPerson(Person): @Person.name.getter def name(self): print('Getting name') return super().name ~~~ 或者,你只想修改setter方法,就这么写: ~~~ class SubPerson(Person): @Person.name.setter def name(self, value): print('Setting name to', value) super(SubPerson, SubPerson).name.__set__(self, value) ~~~ >[danger] ##### 直接定义报错 ~~~ class SubPerson(Person): @property # Doesn't work def name(self): print('Getting name') return super().name ~~~ 如果你试着运行会发现setter函数整个消失了: ~~~ >>> s = SubPerson('Guido') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "example.py", line 5, in __init__ self.name = name AttributeError: can't set attribute >>> ~~~