我有以下父类:
class A:
def __init__(self, input1):
self.input1=input1
self.new_attrib=(self.input1)/7
还有一个从父类继承的子类:
class B(A):
def __init__(self, input1):
self.input1=input1
A.__init__(self,input1 )
def test1(self):
return self.new_attrib*2
根据OPP,我可以从父类self.new_attrib
继承self.new_attrib属性吗?
从上面的代码输出:'B'对象没有属性new_attrib
然后我在B类的构造函数中尝试了super(B, self).__init__(input1)
,但出现了相同的错误
答案 0 :(得分:0)
使用super()访问父类
class B(A):
def __init__(self, input1):
self.input1=input1
super().__init__(self,input1 )
def test1(self):
return super().new_attrib*2
答案 1 :(得分:-1)
您必须区分class attributes
和instance attributes
。
在代码中,您可以通过分配给instance attribute
在__init__()
中创建一个self
。
如果您创建Class的实例,将会看到instance属性可用。
b = B(42)
print(b.test1())
我认为您正在使用B.new_attrib
检查的是,如果您的Class B
有一个属性,该属性检查是否有class attributes
,而在您的构造中不是这种情况。>
要创建一个类属性(在所有实例中共享),请使用以下方法:
def A():
my_class_attribute = 42
def __init__(self):
self.my_instance_attribute = 43