Return from inheritance
How I update x.test to have values return from inheritance ?
So I want x.test return ['test from B'', 'test from C']
class A()
def __init__(self)
self.test = []
return
def coolThings(self):
# do cool things here and print the new self.test
print self.test
class B(A)
def __init__(self)
A.__init__(self)
return
def doSomething(self)
self.test.append('test from B')
class C(A)
def __init__(self)
A.__init__(self开发者_如何学Python)
return
def doAnotherthing(self)
self.test.append('test from C')
--
In [575] x = A()
In [576] y = B()
In [577] z = c()
In [582] y.doSomething()
In [583] z.doAnotherthing()
In [584] x.test
Out[584] []
In [585] y.test
Out[585] ['test B']
In [586] z.test
Out[586] ['test C']
x.coolThings()
??
So again How update x.test to have ['test from B'', 'test from C']
But again how can I mantain self.test in all inheritance? So If I call z.test after y.doSomething() I would like to have ['test from B']
Regards
Inheritance creates relationships between classes, not objects. In your example the classes (A
, B
and C
) are related, but the objects (x
, y
and z
) are not.
Tell us what you're trying to do, and we should be able to help you come up with a good way to do it.
There are two issues here: inheritance, and static data
You have a static data issue. If you want all instances of A and all instances of its children to share a TEST attribute, make it static on the class like this:
class A(object):
test = []
def coolThings(self):
# do cool things here and print the new self.test
print self.test
Inheritance is a different animal. Inheritance just lets you give all children of A copies of A's methods. This is not about sharing data, it's about sharing/extending functionality.
Inheritance doesn't work like that. Try this way:
x = C()
x.doSomething()
x.doAnotherThing()
x.test
Inheritance work the other way, you can't have a base class compound statements from inherited classes.
I'm not sure what you're trying to accomplish but to have separate inherited objects influence the base class, you might use class variables but keep in mind all instances will now have the same test value in this case.
class A():
test = []
def coolThings(self):
print test
class B(A):
def doSomething(self):
A.test.append('test from B')
I repeat again, ALL instances of A and B for that matter will have the same value for test.
精彩评论