欢迎光临haoge的随笔小屋

菜单栏:

继承与多态

继承与多态

继承

class Contact:
    '''
    一个含有name与email的联系人集合类
    '''
all_contact = ContactList()

    def __init__(self, name, email):
        self.name = name
        self.email = email
        self.all_contact.append(self)

class Supplier(Contact):

    '''
    一个含有order方法的商贩联系人集合类
    ''' 

    def order(self, order):
        print('I am {} , order to {}'.format(self.name, order))


class ContactList(list):
    '''
        自定义list,添加search方法
    ''' 

    def search(self, name)
         '''
                返回满足条件的集合
         ''' 
         matching_contacts = []
         for contact in self:
              if name == contact.name:
                    matching_contacts.append(contact)
         return matching_contacts


class Firend(Contact):
    ''' 
        增添iphone属性,重写__init__
    '''

    def __init__(self, name, email, iphone):
        super().__init__(name, email)
        self.iphone = iphone





>>> a = Contact('yes','2131321')
>>> b = Contact('no','1121293')
>>> c = Contact('now','12131')
>>> [a.name for a in Contact.all_contact.search('no')]
['no', 'now']

多链继承问题:

eg:

当多个超类同时指向另一个超类,可能重复初始化

解决方法:

super同一层次的超类只初始化一次

初始化参数问题

解决方法:

1. 在初始化链条中,增加参数字典

多态

python


class animal:
    def __init__(self):
        print('{}叫'.format(self.name))


class dog(animal):
    name = '狗'
    def __init__(self):
        super().__init__()
        print('汪汪汪')


class maomi(animal):
    name = '猫'
    def __init__(self):
        super().__init__()
        print('嘎嘎嘎')



>>> a =dog()
狗叫
汪汪汪
>>> b=maomi()
猫叫
嘎嘎嘎