Reputation: 219
I have a class with a property method:
class SomeClass(object):
@property
def some_method(self):
return True
I want to make a call to some_method and store it in as an expression.
For example:
some_expr = SomeClass().some_method
Should not store the value True in some_expr; rather should store the expression SomeClass().some_method so that it is callable.
How can I implement this?
Upvotes: 3
Views: 1194
Reputation: 95873
Note, you essentially want to use the .__get__
callable on the property instance. However, this will require an instance as the first argument, so you could just partially apply some instance:
In [6]: class SomeClass(object):
...:
...: @property
...: def some_method(self):
...:
...: return True
...:
In [7]: from functools import partial
Then something like:
In [9]: some_exp = partial(SomeClass.some_method.__get__, SomeClass())
In [10]: some_exp()
Out[10]: True
Upvotes: 2
Reputation: 9977
So- a "property" is a descriptor. What this means is it is an object (everything is an object in python) that has the get method defined. When you access a class property, if the object there has the get method, python will helpfully call it for you. That decorator takes the provided function and turns it into a get(self) method on an object that gets assigned to the class. Great!
If, for some reason, you actually wanted the function instead of for the function to get called, you can access it through the class dictionary...
f = SomeClass.__dict__['some_method'].__get__
Which, would allow you to do f(1)
if the "self" method didn't matter.
If you really wanted to get fancy, you could do new_f = functools.partial(f, SomeClass())
Then... new_f() == True
Really curious why you would want to do this though ;)
Upvotes: 0
Reputation: 9946
an easy way to do this is to do something like:
call_prop = lambda: SomeClass().some_prop
but there's no good reason you would ever need this.
Upvotes: 0
Reputation: 49774
Here is one way to make a property callable:
class CallableProperty(object):
def __init__(self, instance, name):
self.instance = instance
self.name = name
def __call__(self):
return getattr(self.instance, self.name)
class SomeClass(object):
@property
def some_method(self):
return True
x = SomeClass()
y = CallableProperty(x, 'some_method')
print(y())
True
Upvotes: 1