【发布时间】:2012-02-28 09:16:59
【问题描述】:
如何根据某些条件动态地向类添加函数。
对于前我有一个类如下:
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
我无法弄清楚我在哪里犯了错误。在合并这个之前,我用一个简单的 sn-p 尝试了这个例子,但是当我在实际代码中做同样的事情时,它会抛出错误。 请帮忙
【问题讨论】:
-
“元类是比 99% 的用户所担心的更深层次的魔法。如果你想知道是否需要它们,其实你不需要。” - TP。您愿意解释一下为什么需要这种行为吗?也许有更好的设计可以帮助您。
标签: python metaprogramming python-2.7 python-2.6 python-2.x