Reputation: 13467
One can add a method to a python class with:
class foo(object):
pass
def donothing(self):
pass
foo.y = donothing
Then one would call the method with:
f = foo()
f.y()
Is there a way to add @property
to the def
as well, so to call it with
f.y
?
Upvotes: 1
Views: 60
Reputation: 195
Absolutely, It can be specified as :
class foo(object):
def __int__(self):
self._y = None
@property
def y(self):
return self._y
@y.setter
def y(self, value):
self._y = value
>>>>x = foo()
>>>>x.y = str
>>>>print type(x.y(12.345)), x.y(12.345)
<type 'str'> 12.345
Here, I'm just saying that the attribute y (yes an attribute and not a method !), is set to value. Since everything is an object in Python, I can perfectly assign a function to a variable. The method associated with the attribute y (there as a property), returns the value of the attribute, which turns to be a function (str in this case). The returned value is used as a callable, which is exactly what we expected. Though, accessing the attribute y returns as a callable, effectively calling str()
I can assign any fucntion to y like this :
def double(x):
return 2 * x
...
>>>>x.y = double
>>>>print x.y(33)
66
And so on...
Upvotes: 0
Reputation: 5326
You can just add the @property before the method definition
... class Foo(object):
... pass
...
>>> @property
... def bar(self):
... print("bar is called")
...
>>> Foo.bar = bar
>>> f = Foo()
>>> f.bar
bar is called
Upvotes: 1