I want to add some attributes and methodes into various class. The methodes and attributes that I have to add are the same but not the class to assign them, so I want to construct a class who assign new methodes and attribute for a class given in argument. I try this but it's not working: (I know that is a very wrong way to try to assign something to self, it's just to show what I want to do)
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()
The result is :
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'
And I expected to got 'a' for the call of instb.gettattB()
To resume I want to inherit class B from class A giving class A in argument of class B because my class B will be a subclass of various class, not always A.
Since B is not a subclass of A, there is no path in B to getatt() in A
I was having trouble with calling different constructors, using
super
doesn't necessarily make sense in a case like this, I opted to inherit and call each constructor on the current object manually:The Best answer is in the comments, it was useful for me so I decided to show it in an answer (thank to sr2222): The way to dynamicaly declare inherance in Python is the type() built-in function. For my example :
The code return :
My class C inerhite attributes and methods of class A and class B and we add c attribute. With the instanciation of C (instc = C('args')) The init for A is call but not for B.
Very useful for me because I have to add some attributes and methodes (the same) on different class.
How about this?
But method in class A can not access attr in class B.
Another way:
Slow with init but call fast.
I'm not certain what you are trying to do, but the code below is giving my the output I think you are expecting. notice:
Code: