013: class and objects > 简单继承

1. 所有的class全部直接或者间接的继承与object.

2. super()方法可以用来访问父类的方法,如果子类拥有和父类同名的方法,则子类会重写父类的方法。

3. 类的引用类型的成员变量定义后,所有的子子孙孙共享一个成员变量

class Contact(object):
    # 引用类型的类级别成员变量
    contact_list = []
    def __init__(self, name, email, telephone):
        # 值类型的对象级别成员变量
        self.name = name
        self.email = email
        self.telephone = telephone

        Contact.contact_list.append(self)    

Contact_A = Contact('Tom', 'tom@gmail.com', 123456)
Contact_B = Contact('Lucy', 'lucy@gmail.com', 123457)

print('Contact:')
for c in Contact.contact_list:
    print(c.name)        


class Friend(Contact):
    friend_list = []
    # 重写父类的方法
    def __init__(self, name, email, telephone, age):
        # 调用父类的方法
        super(Friend, self).__init__(name, email, telephone)
        self.age = age
        Friend.friend_list.append(self)
                    
Friend_A = Friend('Jack', 'jack@gmail.com', 123458, 22)
Friend_B = Friend('Jim', 'jim@gmail.com', 123459, 23)    

# It is a little strange that the child class has quite the same contact_list
print(Contact.contact_list)    
print(Friend.contact_list)

print('Friends:')

for f in Friend.friend_list:
    print(f.name, f.age)            
原文地址:https://www.cnblogs.com/jcsz/p/5122951.html