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

Kyo Guan kguan at corp.netease.com
Fri Aug 12 00:22:17 EDT 2005


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>





More information about the Python-list mailing list