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

K

kyo guan

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

<unbound method Foo.f>

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

Steven Bethard

kyo said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top