我正在观看Bucky's Python Programming教程。他解释了子类和父类的概念,如下所示:
class Dad:
var1 = "Hey I'm Dad"
class Mum:
var2 = "Hey I'm Mum"
class Child(Mum, Dad):
var3 = "Hey I'm a Child"
这,我完全理解。然而,他然后将类转换为对象:
childObject = Child()
dadObject = Dad()
如果他可以致电Child.var3
以获得与childObject.var3
相同的结果,为什么他会这么做呢?
答案 0 :(得分:3)
更好的例子是
class Person:
name="Person"
def speak(self):
print "Hi! Im %s"%slf.name
class Dad(Person):
name = "Dad"
class Mom(Person):
name = "Mom"
class Child(Person):
name = "a Child"
age = 5
def speak(self):
print "Hewwo, I am a %d year old child!"%self.age
d = Dad()
m = Mom()
c = Child()
c.speak()
m.speak()
d.speak()
关于差异(您的静态类访问与实例访问的问题)
class Child:
var3 = "whatever"
c = Child()
c.var3 = "something_else"
print c.var3
print Child.var3