基于 Python 标准的动态函数添加到类中

标签 python metaprogramming python-2.7 python-2.6 python-2.x

如何根据某些条件向类动态添加函数。

例如,我有一个类如下:

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

我不知道我在哪里犯了错误。在合并这个之前,我用一个简单的片段尝试了这个例子,但是当我在实际代码中做同样的事情时,它会抛出错误。 请帮忙

最佳答案

您的问题似乎是 XY Problem ,而你原来的问题“X”的解决方案是多重继承,比如:

class A(B, C):
    pass

现在您可以执行 A().fun1() 以及 A().fun3()

关于基于 Python 标准的动态函数添加到类中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9479211/

相关文章:

python - setuptools 如何构建扩展,在哪里添加编译器选项?

java - 使用 ruby​​ python perl java 或其他方式进行谷歌优化的脚本驱动自动化

python - 如果使用python在捕获区域中存在某些颜色,如何返回 bool 值

ruby - 在 Ruby 的 DSL 中使用 procs

python - 如何在web2py中创建用户定义的类

python - 如何在python中为接口(interface)分配IP地址?

python - 是否有与 Python 的 for-else 语句等效的 Fortran 语句?

Java 代码生成(元编程、反射、wtv)

c++ - 使用除特化之外的默认特征

python - 将多行连接到 Pandas 中的一行