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‘, ‘[email protected]‘, 123456) Contact_B = Contact(‘Lucy‘, ‘[email protected]‘, 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‘, ‘[email protected]‘, 123458, 22) Friend_B = Friend(‘Jim‘, ‘[email protected]‘, 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)
时间: 2024-10-07 22:24:24