Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

How to Adding Functionality to a Class by metaclass(not by inherit)

1 view
Skip to first unread message

Kyo Guan

unread,
Aug 12, 2005, 12:22:17 AM8/12/05
to pytho...@python.org
How to Adding Functionality to a Class by metaclass(not by inherit)

#example:

import inspect

class Foo(object):
def f(self):
pass

def g(self):
pass

class MetaFoo(type):
def __init__(cls, name, bases, dic):
super(MetaFoo, cls).__init__(name, bases, dic)

for n, f in inspect.getmembers(Foo, inspect.ismethod):
setattr(cls, n, f)

#Bar want to achieve Foo's part/all functionality, but not by inherit

class Bar(object):
__metaclass__ = MetaFoo


>>> b = Bar()
>>> b.f()
TypeError: unbound method f() must be called with Foo instance as first argument (got nothing instead)
>>> Bar.f
<unbound method Foo.f>
>>> b.f
<unbound method Foo.f>

how can I set Bar.f as <unbound method Bar.f>


kyo guan

unread,
Aug 12, 2005, 12:25:34 AM8/12/05
to pytho...@python.org

Steven Bethard

unread,
Aug 12, 2005, 12:55:12 AM8/12/05
to
kyo guan wrote:
> How to Adding Functionality to a Class by metaclass(not by inherit)
>
[snip]

>
> class MetaFoo(type):
> def __init__(cls, name, bases, dic):
> super(MetaFoo, cls).__init__(name, bases, dic)
>
> for n, f in inspect.getmembers(Foo, inspect.ismethod):
> setattr(cls, n, f)
^^^^^^^^^
f.im_func

See if that works. I think it should.

But the real question is why you want to do this. Why can't you just
inherit from Foo?

STeVe

Paolino

unread,
Aug 12, 2005, 7:09:45 AM8/12/05
to kyo guan, pytho...@python.org
Dont' know where are you going with that but if what you need is
cancelling some attributes when inheriting then probably this is a
cleaner approach:

class Meta(type):


def __init__(cls, name, bases, dic):

def attributeError(*_):
raise AttributeError
for base in bases:
for dont in base.privates:
setattr(cls,dont,attributeError) #override private methods

class Foo(object):
privates=('f',)


def f(self):
pass
def g(self):
pass

class Bar(Foo):
__metaclass__ = Meta

b=Bar()
b.g()
b.f()

and it implies writing only one metaclass.




___________________________________
Yahoo! Mail: gratis 1GB per i messaggi e allegati da 10MB
http://mail.yahoo.it

0 new messages