I'd like for an attribute call like object.x
to return the results of some method, say object.other.other_method()
. How can I do this?
Edit: I asked a bit soon: it looks like I can do this with
object.__dict__['x']=object.other.other_method()
Is this an OK way to do this?
Attributes of a class can also be accessed using the following built-in methods and functions : getattr() – This function is used to access the attribute of object. hasattr() – This function is used to check if an attribute exist or not. setattr() – This function is used to set an attribute.
The __call__ method enables Python programmers to write classes where the instances behave like functions and can be called like a function. When the instance is called as a function; if this method is defined, x(arg1, arg2, ...) is a shorthand for x. __call__(arg1, arg2, ...) .
A variable stored in an instance or class is called an attribute. A function stored in an instance or class is called a method.
Python getattr() function. Python getattr() function is used to get the value of an object's attribute and if no attribute of that object is found, default value is returned. Basically, returning the default value is the main reason why you may need to use Python getattr() function.
Use the property decorator
class Test(object): # make sure you inherit from object
@property
def x(self):
return 4
p = Test()
p.x # returns 4
Mucking with the __dict__ is dirty, especially when @property is available.
Have a look at the built-in property function.
Use a property
http://docs.python.org/library/functions.html#property
class MyClass(object):
def __init__(self, x):
self._x = x
def get_x(self):
print "in get_x: do something here"
return self._x
def set_x(self, x):
print "in set_x: do something"
self._x = x
x = property(get_x, set_x)
if __name__ == '__main__':
m = MyClass(10)
# getting x
print 'm.x is %s' % m.x
# setting x
m.x = 5
# getting new x
print 'm.x is %s' % m.x
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With