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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM