Python类的构造方法及继承问题

构造方法名字固定为__init__,在创建对象时会自动调用,用于实现类的初始化:

>>> class Person:
...     def __init__(self, name, age=0):
...             self.name = name
...             self.age = age
...     def get_name(self):
...             return self.name
...     def set_name(self, name):
...             self.name = name
...     def get_age(self):
...             return self.age
...     def set_age(self, age):
...             self.age = age
...
>>> p = Person('韩晓萌','21')
>>> p.get_name()
'韩晓萌'
>>> p.get_age()
'21'
>>>

如果子类重写了__init__方法,那么在方法内必须显式的调用父类的__init__方法:

# 没有调用父类的__init__方法
>>> class Man(Person): ... def __init__(self, length): ... self.length = length ... def get_length(self): ... return self.length ... def set_length(self, length): ... self.length = length ... >>> m = Man('18cm') >>> m.get_length() '18cm' >>> m.get_name() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 6, in get_name AttributeError: 'Man' object has no attribute 'name' # 调用了父类的__init__方法 >>> class Woman(Person): ... def __init__(self, name, age=0, cup='A'): ... super().__init__(name, age) ... self.cup = cup ... def get_cup(self): ... return self.cup ... def set_cup(self, cup): ... self.cup = cup ... >>> w = Woman('杨超越', 21, 'C') >>> w.get_cup() 'C' >>> w.get_name() '杨超越' >>> w.get_age() 21
原文地址:https://www.cnblogs.com/hanxiaomeng/p/12711081.html