Python @property装饰器不起作用 [英] Python @property decorator not working

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

问题描述

有人可以发现这个@property装饰器有问题吗?我似乎无法正确断言。我确定我做错了一些非常简单的事情,但是任何人都可以将疲倦的眼睛指向正确的方向吗?

Could anyone find a problem with this @property decorator? I cannot seem to get it to assert correctly. I'm sure I'm doing some really simple thing wrong, but can anyone point my tired eyes in the right direction please?

class A:
    def __init__(self):
        self.a = 0
        self._b = 0

    @property
    def b(self):
        return self.b

    @b.getter
    def b(self):
        if self._b is None:
            return 0
        return self._b

    @b.setter
    def b(self, val):
        self._b = (val * 20)


def test_getter_setter():
    obj = A()
    obj.a = 1
    #obj.b = 2
    print obj.a, obj.b
    obj.b = 2
    print obj.a, obj.b
    assert obj.b == 40

test_getter_setter()


推荐答案

@property 装饰器仅适用于新样式类。从 object 继承:

The @property decorator only works on new style classes. Inherit from object:

class A(object):

通过此更改,测试功能将通过。

With that change your test function passes.

这篇关于Python @property装饰器不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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