我想在各个类中添加一些属性和方法.我必须添加的方法和属性是相同的,但不是分配它们的类,所以我想构建一个为参数中给出的类分配新的方法和属性的类.我尝试了这个但它不起作用:(我知道这是一种非常错误的方法,试图给自己分配一些东西,这只是为了表明我想做什么)
class A:
def __init__(self):
self.a = 'a'
def getatt(self):
return self.a
class B:
def __init__(self, parent) :
self = parent
# This is working :
print self.getatt()
def getattB(self):
return self.getatt()
insta = A()
instb = B(insta)
# This is not working :
print instb.getattB()
Run Code Online (Sandbox Code Playgroud)
结果是:
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.getatt()
AttributeError: B instance has no attribute 'getatt' …Run Code Online (Sandbox Code Playgroud)