为什么Python中的@ foo.setter对我不起作用? [英] Why does @foo.setter in Python not work for me?

查看:166
本文介绍了为什么Python中的@ foo.setter对我不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我正在使用Python 2.6中的装饰器,但在使它们工作时遇到了一些麻烦。这是我的课程文件:

So, I'm playing with decorators in Python 2.6, and I'm having some trouble getting them to work. Here is my class file:

class testDec:

    @property
    def x(self): 
        print 'called getter'
        return self._x

    @x.setter
    def x(self, value): 
        print 'called setter'
        self._x = value

我认为这意味着要治疗 x 就像一个属性,但是在get和set上调用这些函数。因此,我启动了IDLE并进行了检查:

What I thought this meant is to treat x like a property, but call these functions on get and set. So, I fired up IDLE and checked it:

>>> from testDec import testDec
from testDec import testDec
>>> t = testDec()
t = testDec()
>>> t.x
t.x
called getter
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "testDec.py", line 18, in x
    return self._x
AttributeError: testDec instance has no attribute '_x'
>>> t.x = 5
t.x = 5
>>> t.x
t.x
5

由于我调用getter,并且没有默认值,并且它将失败。好,很好,我了解。但是,调用 tx = 5 的调用似乎会创建一个新属性 x ,而现在的getter并没有

Clearly the first call works as expected, since I call the getter, and there is no default value, and it fails. OK, good, I understand. However, the call to assign t.x = 5 seems to create a new property x, and now the getter doesn't work!

我缺少什么?

推荐答案

您似乎使用经典的老式类在python 2中。为了获得属性要正常工作,您需要使用新型类(在python 2中,您必须继承自 object )。只需将您的类声明为 MyClass(object)

You seem to be using classic old-style classes in python 2. In order for properties to work correctly you need to use new-style classes instead (in python 2 you must inherit from object). Just declare your class as 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.x
called getter
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/devel/class_test.py", line 6, in x
    return self._x
AttributeError: 'testDec' object has no attribute '_x'
>>> k.x = 5
called setter
>>> k.x
called getter
5
>>> 

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

Another detail that might cause problems is that both methods need the same name for the property to work. If you define the setter with a different name like this it won't work:

@x.setter
def x_setter(self, value):
    ...

首先,还不容易发现的另一件事是顺序:吸气剂必须首先定义。如果您先定义设置器,则会出现未定义名称 x的情况错误。

And one more thing that is not completely easy to spot at first, is the order: The getter must be defined first. If you define the setter first, you get name 'x' is not defined error.

这篇关于为什么Python中的@ foo.setter对我不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆