[英]Python - How to update base class variable from derived class
[英]How to access an instance variable of a derived class from a base class in Python
我有Python中的下一个代码:
class Base_class():
def __init__(self):
pass
# this is the method where I need help
def compress(variable?,index?):
somecode()
class Derived_class_1():
def __init__(self,somelist):
self.A = []
self.B = []
for item in somelist:
if item == 1:
self.A.append([1,0])
self.B.append([0,1])
else:
self.A.append([1,0])
self.B.append([1,0])
class Derived_class_2():
def __init__(self,somelist):
self.A = []
self.B = []
for item in somelist:
if item == 1:
self.A.append([1,0])
self.B.append([1,0])
else:
self.A.append([1,0])
self.B.append([0,1])
我需要在基类的compress方法中能够访问每个实例值,并基于索引返回一维列表,因为实例变量对于列表中的每个元素都有两个可能的值。 我需要使compress方法成为一类吗? 如果是这种情况,我该如何实现呢?
我的代码有2个问题。
Derrived
类不会从Base_class
继承 compress
缺少self
变化:
class Base_class():
# ...
def compress(self, variable, index):
print(self.A)
print(self.B)
class Derived_class_1(Base_class):
# ...
class Derived_class_2(Base_class):
# ...
然后测试
>>> x = Derived_class_1([1, 2])
>>> x.compress(5, 6)
[[1, 0], [1, 0]]
[[0, 1], [1, 0]]
>>> y = Derived_class_2([1, 2])
>>> y.compress(5, 6)
[[1, 0], [1, 0]]
[[1, 0], [0, 1]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.