美文网首页
习题 42 对象、类及从属关系

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

作者: 南北东西总相随 | 来源:发表于2017-10-14 21:33 被阅读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)
    

    相关文章

      网友评论

          本文标题:习题 42 对象、类及从属关系

          本文链接:https://www.haomeiwen.com/subject/evifuxtx.html