python : How to "merge" two class

标签 python class merge

我想在不同的类中添加一些属性和方法。我必须添加的方法和属性是相同的,但不是分配它们的类,所以我想构造一个类,为参数中给定的类分配新的方法和属性。 我试试这个,但它不工作: (我知道尝试将某些东西分配给自己是一种非常错误的方式,它只是为了展示我想做的事情)

class A:
    def __init__(self):
        self.a = 'a'

    def getattA(self):
        return self.a

class B:
    def __init__(self, parent) :
        self = parent

        # This is working :
        print self.getattA()

    def getattB(self):
        return self.getattA()

insta = A()
instb = B(insta)

# This is not working :
print instb.getattB()

结果是:

a
Traceback (most recent call last):
  File "D:\Documents and settings\Bureau\merge.py", line 22, in <module>
    print instb.getattB()
  File "D:\Documents and settings\Bureau\merge.py", line 16, in getattB
    return self.getattA()
AttributeError: B instance has no attribute 'getattA'

我希望在调用 instb.gettattB() 时得到 'a'

为了恢复,我想从 A 类继承 B 类,在 B 类的参数中给出 A 类,因为我的 B 类将是各种类的子类,而不总是 A。

最佳答案

最佳答案在评论中,它对我很有用,所以我决定在答案中展示它(感谢 sr2222): 在 Python 中动态声明继承的方法是 type() 内置函数。 对于我的例子:

class A(object) :
    def __init__(self, args):
        self.a = 'a'
        self.args = args

    def getattA(self):
        return self.a, self.args

class B(object) :
    b = 'b' 
    def __init__(self, args) :
        self.b_init = args

    def getattB(self):
        return self.b

C = type('C', (A,B), dict(c='c'))

instc = C('args')

print 'attributes :', instc.a,  instc.args, instc.b, instc.c
print 'methodes :', instc.getattA(), instc.getattB()

print instc.b_init

代码返回:

attributes : a args b c
methodes : ('a', 'args') b
Traceback (most recent call last):
  File "D:\Documents and settings\Bureau\merge2.py", line 24, in <module>
    print instc.b_init
AttributeError: 'C' object has no attribute 'b_init'

我的类 C 继承了类 A 和类 B 的属性和方法,我们添加了 c 属性。随着 C 的实例化 (instc = C('args')) A 的 init 是调用,但 B 不是。

对我来说非常有用,因为我必须在不同的类上添加一些属性和方法(相同)。

关于 python : How to "merge" two class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9667818/

相关文章:

python - 如何从输入数据集中删除非数字列?

c# - 在 WPF 中,在项目中使用 Struct 或 Class 作为具有 MVVM 模式的模型?

c - 合并 - 比较 - 输出 (C)

java - 如何将列表中的两个项目合并为一个?

python - numpy 将不同类型的数组保存到文本文件中

python - Elasticsearch-根据 'hit'返回结果,而不是文档

Javascript:如何从对象定义(如类)正确创建新的自定义实例

algorithm - 理解归并排序的递归

python - Snow Leopard 上的 SQLite 最大查询参数不同?

python - 如何使用 Tkinter 中的类创建新页面?