var1
and var2
are instance variables. That means that you have to send the instance of ClassA
to ClassB
in order for ClassB to access it, i.e:
class ClassA(object):
def __init__(self):
self.var1 = 1
self.var2 = 2
def methodA(self):
self.var1 = self.var1 + self.var2
return self.var1
class ClassB(ClassA):
def __init__(self, class_a):
self.var1 = class_a.var1
self.var2 = class_a.var2
object1 = ClassA()
sum = object1.methodA()
object2 = ClassB(object1)
print sum
On the other hand - if you were to use class variables, you could access var1 and var2 without sending object1 as a parameter to ClassB.
class ClassA(object):
var1 = 0
var2 = 0
def __init__(self):
ClassA.var1 = 1
ClassA.var2 = 2
def methodA(self):
ClassA.var1 = ClassA.var1 + ClassA.var2
return ClassA.var1
class ClassB(ClassA):
def __init__(self):
print ClassA.var1
print ClassA.var2
object1 = ClassA()
sum = object1.methodA()
object2 = ClassB()
print sum
Note, however, that class variables are shared among all instances of its class.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…