Add @property method to a class

75 views Asked by At

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

?

3

There are 3 answers

0
Yoann Quenach de Quivillic On BEST ANSWER

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
0
falsetru On

Assign the return value of the property:

>>> class foo(object):
...     pass
...
>>> def donothing(self):
...     print('donothing is called')
...
>>> foo.y = property(donothing)  # <----
>>> f = foo()
>>> f.y
donothing is called
1
dcexcal On

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...