为什么Python中的@ foo.setter对我不起作用?

为什么Python中的@ foo.setter对我不起作用?,第1张

为什么Python中的@ foo.setter对我不起作用?

您似乎在python 2中使用经典的老式类。为了使属性正常工作,您需要使用新型类(在python
2中,您必须继承自

object
)。只需将您的课程声明为
MyClass(object)

class testDec(object):    @property    def x(self):         print 'called getter'        return self._x    @x.setter    def x(self, value):         print 'called setter'        self._x = value

有用:

>>> k = testDec()>>> k.xcalled getterTraceback (most recent call last):  File "<stdin>", line 1, in <module>  File "/devel/class_test.py", line 6, in x    return self._xAttributeError: 'testDec' object has no attribute '_x'>>> k.x = 5called setter>>> k.xcalled getter5>>>

可能导致问题的另一个细节是,这两种方法都需要相同的名称才能使该属性起作用。 如果您使用类似这样的其他名称来定义设置器,它将无法正常工作

@x.setterdef x_setter(self, value):    ...

首先,还不完全容易发现的另一件事是顺序: 必须先定义 吸气剂。如果首先定义设置器,则会

name 'x' is not defined
出错。



欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5617601.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-15
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存