习题 42 对象、类及从属关系

2017-10-14  本文已影响0人  南北东西总相随

习题 42 对象、类及从属关系

class Animal(object):
    def __init__(self, name):
        self.name = name

class Dog(Animal):
    pass

class Cat(Animal):
    pass

class Person(object):
    def __init__(self, name):
        self.name = name
        self.pet = None

class Employee(Person):
    def __init__(self, name, salary):
        super(Employee, self).__init__(name)
        self.salary = salary

rover = Dog('Rover')
satan = Cat('Satan')

mary = Person('Mary')
mary.pet = satan

frank = Employee('Frank', 120000)
frank.pet = rover

print "%s has a cat named %s." % (mary.name, mary.pet.name)

print "%s's salary is %d. He has a dog named %s." % (frank.name, frank.salary, frank.pet.name)

结果:

Mary has a cat named Satan.
Frank's salary is 120000. He has a dog named Rover.

调用父类的初始化方法

super(Employee, self).__init__(name)
上一篇下一篇

猜你喜欢

热点阅读