Using Python () Property Inside Method

Assuming you know about Python's built-in property: http://docs.python.org/library/functions.html#property

I want to redefine the property of an object in this way, but I need to do this inside the method in order to be able to pass some arguments to it, currently all web examples of property () define the property outside the methods and try the obvious ...

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

... doesn't seem to work, I'm glad if you can show me my conceptual error or other alternative solutions without subclassing the code (in fact my code is already reclassified) or using decorators (I’ll use this solution if there is no other )

Thanks.

+2
source share
2 answers

Properties work using a descriptor protocol that only works with attributes of a class object. The property object must be stored in the class attribute. You cannot "override" it for each instance.

You can, of course, provide a class property that receives an instance attribute or reverts to some by 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 
+4
source

In this case, all you need to do in alpha() is self.x = beta . Use a property if 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 
+1
source

Source: https://habr.com/ru/post/895622/


All Articles