Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: How to make object attribute refer call a method

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?

like image 475
mellort Avatar asked Jul 02 '10 14:07

mellort


People also ask

How do you call an object attribute in Python?

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.

What is __ call __ method in Python?

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

What is the syntactical difference between calling a method and an attribute on an object?

A variable stored in an instance or class is called an attribute. A function stored in an instance or class is called a method.

How do you get data from an object in Python?

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.


3 Answers

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.

like image 191
Donald Miner Avatar answered Oct 27 '22 15:10

Donald Miner


Have a look at the built-in property function.

like image 28
muksie Avatar answered Oct 27 '22 13:10

muksie


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
like image 25
Gary Kerr Avatar answered Oct 27 '22 14:10

Gary Kerr