一、派生
派生:子類中新定義的屬性的這個過程叫做派生,並且需要記住子類在使用派生的屬性時始終以自己的爲準
1 派生方法一(類調用)
指名道姓訪問某一個類的函數:該方式與繼承無關
class OldboyPeople:
"""由於學生和老師都是人,因此人都有姓名、年齡、性別"""
school = 'oldboy'
def __init__(self, name, age, gender):
self.name = name
self.age = age
self.gender = gender
class OldboyStudent(OldboyPeople):
"""由於學生類沒有獨自的__init__()方法,因此不需要聲明繼承父類的__init__()方法,會自動繼承"""
def choose_course(self):
print('%s is choosing course' % self.name)
class OldboyTeacher(OldboyPeople):
"""由於老師類有獨自的__init__()方法,因此需要聲明繼承父類的__init__()"""
def __init__(self, name, age, gender, level):
OldboyPeople.__init__(self, name, age, gender)
self.level = level # 派生
def score(self, stu_obj, num):
print('%s is scoring' % self.name)
stu_obj.score = num
stu1 = OldboyStudent('tank', 18, 'male')
tea1 = OldboyTeacher('nick', 18, 'male', 10)
print(stu1.__dict__)
{'name': 'tank', 'age': 18, 'gender': 'male'}
print(tea1.__dict__)
{'name': 'nick', 'age': 18, 'gender': 'male', 'level': 10}
2 派生方法二(super)
- 嚴格以來繼承屬性查找關係
- super()會得到一個特殊的對象,該對象就是專門用來訪問父類中的屬性的(按照繼承的關係)
- super().
__init__
(不用爲self傳值) - super的完整用法是super(自己的類名,self),在python2中需要寫完整,而python3中可以簡寫爲super()
class OldboyPeople:
school = 'oldboy'
def __init__(self, name, age, sex):
self.name = name
self.age = age
self.sex = sex
#學習中遇到問題沒人解答?小編創建了一個Python學習交流羣:711312441
class OldboyStudent(OldboyPeople):
def __init__(self, name, age, sex, stu_id):
# OldboyPeople.__init__(self,name,age,sex)
# super(OldboyStudent, self).__init__(name, age, sex)
super().__init__(name, age, sex)
self.stu_id = stu_id
def choose_course(self):
print('%s is choosing course' % self.name)
stu1 = OldboyStudent('tank', 19, 'male', 1)
print(stu1.__dict__)
{'name': 'tank', 'age': 19, 'sex': 'male', 'stu_id': 1}