Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing function as attribute in a Python class

I'm in a situation where it would be extremely useful (though not strictly necessary) to access a class' instancemethod as an attribute. (it's for an API that uses getattr to set some return values for a dictionary and I don't want to mess the neat little thing up)

I remember reading something about an @attribute decorator, but I can't find one (either in Python or Django)

TL;DR:

How do I make this:

class foo:     bar = "bar"     def baz(self):         return "baz" 

do this:

>>> f = foo() >>> f.baz "baz" 

(edit for clarity) instead of this:

>>> f = foo() >>> f.baz <bound method foo.baz of <__builtin__.foo instance at 0x...>> 
like image 302
Brian Hicks Avatar asked Apr 18 '11 15:04

Brian Hicks


People also ask

How do you access a function inside a class in Python?

To call a function within class with Python, we call the function with self before it. We call the distToPoint instance method within the Coordinates class by calling self. distToPoint . self is variable storing the current Coordinates class instance.

Can a function be a class attribute?

The attribute A.f was defined as part of the class. It is a function, so it is by default an instance method of that class. Creating an instance (named a ) of class A causes that instance to have an attribute f , and you access that by the name a.f .

Can a function be an attribute?

In python, functions too are objects. So they have attributes like other objects. All functions have a built-in attribute __doc__, which returns the doc string defined in the function source code. We can also assign new attributes to them, as well as retrieve the values of those attributes.


2 Answers

You can use the @property decorator.

class foo(object):     bar = "bar"     @property     def baz(self):         return "baz" 
like image 173
Praveen Gollakota Avatar answered Oct 09 '22 14:10

Praveen Gollakota


Take a look at the decorator form of property.

@property def baz(self):   return "baz" 
like image 32
SteveMc Avatar answered Oct 09 '22 15:10

SteveMc