[Tutor] __getattr__ can't be a staticmethod?
Kent Johnson
kent37 at tds.net
Sat May 24 14:02:22 CEST 2008
On Sat, May 24, 2008 at 2:45 AM, inhahe <inhahe at gmail.com> wrote:
> On Fri, May 23, 2008 at 10:47 PM, Kent Johnson <kent37 at tds.net> wrote:
>> On Fri, May 23, 2008 at 7:52 PM, inhahe <inhahe at gmail.com> wrote:
>>> why doesn't this work?
>>>
>>>>>> class a:
>>> ... @staticmethod
>>> ... def __getattr__(attr):
>>> ... return "I am a dork"
>>> ...
>>>>>> f = a()
>>>>>> f.hi
>>> Traceback (most recent call last):
>>> File "<stdin>", line 1, in <module>
>>> TypeError: 'staticmethod' object is not callable
>>
> I wanted to set getattr on a class. I don't need an object. I'm not
> really getting anything
> specific to the class or an object of it. i'm using it because f.hi()
> is easier than f('hi')().
In your example, f is an instance and normal getattr would do what you
want. For example:
class a:
def __getattr__(self, attr):
return "I am a dork"
f = a()
print f.hi
prints "I am a dork"
If you want to be able to ask for a.hi then you need a metaclass - you
have to define __getattr__() in the class of a, which is its
metaclass:
class meta(type):
def __getattr__(self, attr):
return "I am a dork"
class b(object):
__metaclass__ = meta
print b.hi
Kent
More information about the Tutor
mailing list