Accessing function as attribute in a Python class
Question:
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...>>
Answers:
You can use the @property
decorator.
class foo(object):
bar = "bar"
@property
def baz(self):
return "baz"
Take a look at the decorator form of property.
@property
def baz(self):
return "baz"
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...>>
You can use the @property
decorator.
class foo(object):
bar = "bar"
@property
def baz(self):
return "baz"
Take a look at the decorator form of property.
@property
def baz(self):
return "baz"