Python中继承的特点
- 继承中父类的构造函数不会被自动调用,其需要子类在其自己的构造函数中亲自调用。
#Filenaame: BaseModel.py
# 注意模块名最好和类名取不一样的名字
class BaseClass:
def __init__(self, name, age):
self.name = name
self.age = age
print('baseclass is inited')
def speak(self, sth):
print('baseclass is speak :%s'%sth)
if __name__ == '__main__':
b = BaseClass('yuanCruise',23)
b.speak('PG one')
- 在调用父类的方法时,需要加上父类的类名前缀,且需要带上self参数变量。
import BaseModel
# 该处调用时需要利用 【文件名.类名】
class SubClass(BaseModel.BaseClass):
def __init__(self, name, age, salary):
#调用父类的构造函数,如上述所说的注意点
BaseModel.BaseClass.__init__(self, name, age)
self.salary = salary
print('SubClass is inited and the salary:%s'%self.salary)
def talk(self, sth):
print('In SubClass %s is saying %s'%(self.name, sth))
# 调用父类的方法,如上述所说的注意点
BaseModel.BaseClass.speak(self, sth)
if __name__ == '__main__':
s = SubClass('yuanCruise', 23, 10)
s.talk('JYM')
- 如果子类中没有定义构造函数,则会自动继承父类的构造函数中的属性
import BaseModel
# 该处调用时需要利用 【文件名.类名】
class SubClass(BaseModel.BaseClass):
#def __init__(self, name, age, salary):
#调用父类的构造函数,如上述所说的注意点
#BaseModel.BaseClass.__init__(self, name, age)
#self.salary = salary
#print('SubClass is inited and the salary:%s'%self.salary)
def talk(self, sth):
print('In SubClass %s is saying%s, his age is: %s'%(self.name, sth, self.age))
# 调用父类的方法,如上述所说的注意点
BaseModel.BaseClass.speak(self, sth)
if __name__ == '__main__':
#s = SubClass('yuanCruise', 23, 10)
# 但构造函数的参数一定要输入正确
s = SubClass('yuanCruise', 23)
s.talk('JYM')
COMMEND:
Traceback (most recent call last):
File "C:/Software/pycharm/myPython35_code/daily_code/item1/SubModel.py", line 14, in <module>
s = SubClass('yuanCruise', 23, 10)
TypeError: __init__() takes 3 positional arguments but 4 were given
- 以子类的名义调用函数方法,则调用的过程中先在子类中寻找,若没找到则再去父类中寻找该对应的方法
import BaseModel
# 该处调用时需要利用 【文件名.类名】
class SubClass(BaseModel.BaseClass):
#def __init__(self, name, age, salary):
#调用父类的构造函数,如上述所说的注意点
#BaseModel.BaseClass.__init__(self, name, age)
#self.salary = salary
#print('SubClass is inited and the salary:%s'%self.salary)
def talk(self, sth):
print('In SubClass %s is saying%s, his age is: %s'%(self.name, sth, self.age))
# 调用父类的方法,如上述所说的注意点
BaseModel.BaseClass.speak(self, sth)
if __name__ == '__main__':
#s = SubClass('yuanCruise', 23, 10)
s = SubClass('yuanCruise', 23)
s.talk('JYM')
# 该方法虽然以子类的名义调用,但在子类中未找到该方法所以从父类中寻找并调用
s.speak('PG one')
COMMEND:
baseclass is inited
In SubClass yuanCruise is sayingJYM, his age is: 23
baseclass is speak :JYM
baseclass is speak :PG one