views:

46

answers:

2

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.

+2  A: 

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
Thomas Wouters
A: 

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
Daenyth