6

Here is the code:

def Property(func):
     return property(**func())

class A:
     def __init__(self, name):
          self._name = name

     @Property
     def name():
          doc = 'A''s name'

          def fget(self):
               return self._name

          def fset(self, val):
               self._name = val

          fdel = None

          print locals()
          return locals()

a = A('John')
print a.name
print a._name
a.name = 'Bob'
print a.name
print a._name

Above produces the following output:

{'doc': 'As name', 'fset': <function fset at 0x10b68e578>, 'fdel': None, 'fget': <function fget at 0x10b68ec08>}
John
John
Bob
John

The code is taken from here.

Question: what's wrong? It should be something simple but I can't find it.

Note: I need property for complex getting/setting, not simply hiding the attribute.

Thanks in advance.

4

2 回答 2

8

状态的文档property()

返回新样式类(从对象派生的类)的属性属性。

您的类不是新式类(您没有从对象继承)。将类声明更改为:

class A(object):
    ...

它应该按预期工作。

于 2012-05-25T20:39:16.220 回答
1

(上面发布)使用这种格式: http ://docs.python.org/library/functions.html#property

class C(object):
    def __init__(self):
        self._name = "nameless"

    @property
    def name(self):
        """I'm the 'name' property."""
        return self._name

    @name.setter
    def name(self, value):
        self._name = value

    @name.deleter
    def name(self):
        del self._name
于 2012-05-25T21:43:31.480 回答