继承人归来

2024-04-16 13:03:06 发布

您现在位置:Python中文网/ 问答频道 /正文

如何更新x.test以使值从继承返回?你知道吗

所以我想要x.test返回['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)
        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()
??

那么,如何更新x.test,使其具有['test from B'','test from C']

但我又怎么能坚持呢自检在所有的遗产中?因此,如果我在y.doSomething()之后调用z.test,我希望得到['testfrom B']

敬礼


Tags: infromtestselfreturninitdefout
3条回答

这里有两个问题:继承和静态数据

你有一个静态数据问题。如果希望的所有实例及其子对象的所有实例共享一个TEST属性,请使其在类上保持静态,如下所示:

class A(object):
    test = []

    def coolThings(self):
        # do cool things here and print the new self.test
        print self.test

遗传是另一种动物。继承只允许您将A的方法的副本提供给A的所有子级。这不是关于共享数据,而是关于共享/扩展功能。你知道吗

继承不是这样的。请这样做:

x = C()
x.doSomething()
x.doAnotherThing()
x.test

继承创建类之间的关系,而不是对象之间的关系。在您的示例中,类(ABC)是相关的,但是对象(xyz)不是相关的。你知道吗

告诉我们你想做什么,我们应该能帮你想出一个好办法。你知道吗

相关问题 更多 >