如何根据某些条件向类动态添加函数。
例如,我有一个类如下:
class A(object):
def __init__(self,type):
self.type = type
现在基于“类型”值,我想将 B 类或 C 类中的函数添加到 A 类中。
例如
lass B(object):
def fun1(self):
print 'fun1'
def fun2(self):
print 'fun2'
class C(object):
def fun3(self):
print 'fun3'
def fun4(self):
print 'fun4'
如果 A 类的 'type' 属性值为 'B',则将 B 类的函数(即 fun1 和 fun2)动态添加到 A 类,否则如果 'type' 属性值为 'C',则添加 C 类的函数到 A 类(即 fun3 和 fun4)到 A 类,这样在我的代码中我可以进一步访问这些函数作为 A.fun1() 或 A.fun3。
我猜测元编程可能会在这方面帮助我,但我不知道如何去做。请指导。
此外,我必须创建 A 类对象,并能够通过 A 类对象使用这些函数。
a = class A(type='B')
a.fun1() #should work
请帮忙,因为我无法解决这个问题。
这是我的代码的一部分。
class Group(object):
def __init__(self,type):
if type == 'source'
self.mgr = SManager(self) #grp_mgr
elif type == 'target'
self.mgr = TManager(self)
def __getattr__(self,name):
if hasattr(self.mgr,name):
return getattr(self.mgr,name)
return AttributeError
class SManager(object):
def __init__(self,groupobj):
self.some_list = []
self.groupobj = groupobj
def doProcess(self):
#this function accesses self.groupobj
pass
def get_valid_list(self):
#this function accesses self.groupobj
pass
但是我得到了以下错误。
if hasattr(self.mgr,name):
File "c:\workspace\project\dev.py", line 27, in __ge
tattr__
if hasattr(self.mgr,name):
File "c:\workspace\project\dev.py", line 27, in __ge
tattr__
if hasattr(self.mgr,name):
File "c:\workspace\project\dev.py", line 27, in __ge
tattr__
if hasattr(self.mgr,name):
File "c:\workspace\project\dev.py", line 27, in __ge
tattr__
if hasattr(self.mgr,name):
File "c:\workspace\project\dev.py", line 27, in __ge
tattr__
if hasattr(self.mgr,name):
RuntimeError: maximum recursion depth exceeded while calling a Python object
我不知道我在哪里犯了错误。在合并这个之前,我用一个简单的片段尝试了这个例子,但是当我在实际代码中做同样的事情时,它会抛出错误。 请帮忙
最佳答案
关于基于 Python 标准的动态函数添加到类中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9479211/