Using Python property() inside a method

痴心易碎 提交于 2020-01-22 16:46:26

问题


Assuming you know about Python builtin property: http://docs.python.org/library/functions.html#property

I want to re-set a object property in this way but, I need to do it inside a method to be able to pass to it some arguments, currently all the web examples of property() are defining the property outside the methods, and trying the obvious...

def alpha(self, beta):
  self.x = property(beta)

...seems not to work, I'm glad if you can show me my concept error or other alternative solutions without subclassing the code (actually my code is already over-subclassed) or using decorators (this is the solution I'll use if there is no other).

Thanks.


回答1:


Properties work using the descriptor protocol, which only works on attributes of a class object. The property object has to be stored in a class attribute. You can't "override" it on a per-instance basis.

You can, of course, provide a property on the class that gets an instance attribute or falls back to some default:

class C(object):
    _default_x = 5
    _x = None
    @property
    def x(self):
        return self._x or self._default_x
    def alpha(self, beta):
        self._x = beta



回答2:


In this case all you need to do in your alpha() is self.x = beta. Use property when you want to implement getters and setters for an attribute, for example:

class Foo(object):
    @property
    def foo(self):
        return self._dblookup('foo')

    @foo.setter
    def foo(self, value):
        self._dbwrite('foo', value)

And then be able to do

f = Foo()
f.foo
f.foo = bar


来源:https://stackoverflow.com/questions/3302020/using-python-property-inside-a-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!