属性获取器/设置器在Python 2中无效 [英] Property getter/setter have no effect in Python 2

查看:77
本文介绍了属性获取器/设置器在Python 2中无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对python中的属性有些困惑.考虑以下代码

I'm a bit confused about properties in python. Consider the following code

class A:
    @property
    def N(self):
        print("A getter")
        return self._N
    @N.setter
    def N(self,v):
        print("A setter")
        self._N = v

    def __init__(self):
        self._N = 1

class B:
    @property
    def N(self):
        print("B getter")
        return self.a.N
    @N.setter
    def N(self,v):
        print("B setter")
        self.a.N = v

    def __init__(self):
        self.a = A()

if __name__ == '__main__':
    b=B()
    b.N = 2
    print(b.N, b.a.N)
    b.N = 3
    print(b.N, b.a.N)

B应该像是A的包装器.它使用getter和setter来将A的属性映射到自身(当然,也可以通过继承来实现). 问题是,它在python2.6中根本无法按预期运行,而在python3中却如此:

B should be something like a wrapper for A. It uses getters and setters to map A's properties on itself (of course one could also do it via inheritance). The problem is, that it simply doesn't work as expected in python2.6 while it does in python3:

> python2 test.py
A getter
(2, 1)
A getter
(3, 1)

> python3 test.py
B setter
A setter
B getter
A getter
A getter
2 2
B setter
A setter
B getter
A getter
A getter
3 3

我是在做错什么还是问题在哪里?

Am I doing anything wrong or where exactly is the problem?

推荐答案

A和B必须是Python 2.x中的新型类.

A and B must be new-style classes in Python 2.x.

property([fget[, fset[, fdel[, doc]]]])

返回新样式类(从<一个href ="http://docs.python.org/library/functions.html#object">对象).

因此,如果您从object

class A(object):
   ...

class B(object):
    ...

您的代码将按预期工作.

Your code will work as expected.

这篇关于属性获取器/设置器在Python 2中无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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