【发布时间】:2020-11-28 18:44:00
【问题描述】:
这是我的课程:
class A(Something):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.amounts = []
self.counts = []
def common_method(self):
amounts = self.amounts
counts = self.counts
print(amounts)
class B(A):
def construct(self):
counts = self.counts
amounts = [1, 2, 3, 4]
self.common_method()
当类B 被实例化时,这将导致打印[] 而不是[1, 2, 3, 4]。
如果我从A 中删除amounts = self.amounts,则会收到错误amounts 未定义。从父类A 调用方法common_method 时,如何使B 中设置的金额值保持不变。
谢谢。
【问题讨论】:
-
construct()中的self.common_method缺少()。 -
amounts = [1, 2, 3, 4]应该是self.amounts = [1, 2, 3, 4] -
另外,
B不一定需要自己的__init__()。 -
我的意思是,您似乎也打算发布:
b = B(); b.construct()。 -
我们不能自己运行它,因为我们没有
Something类。这个问题并不重要,因此可以删除它(在A中根本不需要__init__)。目标是一个我们可以在删除不需要的代码的情况下运行的示例。
标签: python python-3.x oop inheritance