習(xí)題 42 對象炭剪、類及從屬關(guān)系
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)
結(jié)果:
Mary has a cat named Satan.
Frank's salary is 120000. He has a dog named Rover.
調(diào)用父類的初始化方法
super(Employee, self).__init__(name)