1

我目前正在观看Bucky 的 Python 编程教程。他解释了子类和父类的概念,如下所示:

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呢?

4

1 回答 1

4

一个更好的例子是

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
于 2013-08-05T23:29:26.550 回答