Unexpected __metaclass__ method behavior

Arnaud Delobelle arnodel at googlemail.com
Mon Dec 31 13:32:44 EST 2007


On Dec 31, 12:06 pm, anne.nospa... at wangnick.de wrote:
> Well, you see, I have some database functions that deal with "things"
> which are either classes or instances thereof. I though polymorphism
> would be a nice way to handle them identically, like:
>
> def do(thing): thing.Foo()
> do(t)
> do(Test)
>
> But never mind, I now understand that Test.__dict__ can contain only
> one entry for 'Foo', and that this must be matched.
>
> Kind regards,
> Sebastian

Of course you can do this.  The trick is *not* to use metaclasses!

class Bar(object):
    def foo(self): return 'instance foo'
    @classmethod
    def classfoo(cls): return 'class foo'

def do(x):
    if isinstance(x, type):
        return x.classfoo()
    else:
        return x.foo()

Then:

>>> bar = Bar()
>>> do(bar)
'instance foo'
>>> do(Bar)
'class foo'

HTH

--
Arnaud






More information about the Python-list mailing list