gpt4 book ai didi

python - 了解父属性 setter 的继承

转载 作者:行者123 更新时间:2023-12-01 09:08:12 25 4
gpt4 key购买 nike

我想在尝试在子类中设置属性时引发NotImplementedError。这是父类的代码:

class Parent():

def __init__(self):
self._attribute = 1

@property
def attribute(self):
return self._attribute

@attribute.setter
def attribute(self, value):
self._attribute = value

我发现我可以定义一个 Child ,它可以通过执行以下任一操作直接覆盖“Parent”的属性 setter :

class ChildA(Parent):

@Parent.attribute.setter
def attribute(self, value):
raise NotImplementedError('Not implemented.')


class ChildB(Parent):

@property
def attribute(self):
return self._attribute

@attribute.setter
def attribute(self, value):
raise NotImplementedError('Not implemented.')

以上有什么区别吗?

最佳答案

这两种解决方案没有区别。

事实上,@property.getter , @property.setter@property.deleter装饰器是根据这个确切的用例精心设计的。来自 the docs :

A property object has getter, setter, and deleter methods usable as decorators that create a copy of the property with the corresponding accessor function set to the decorated function.

(强调我的。)

所以不,使用@Parent.attribute.setter不会影响 Parent 的行为类。

总的来说,最好使用 @Parent.attribute.setter解决方案,因为它减少了代码重复 - 将父类的 getter 复制粘贴到子类中只不过是潜在的错误来源。

<小时/>

相关问题:

关于python - 了解父属性 setter 的继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51874026/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com