继承是类与类之间的关系,当类A继承了类B时,类A称为类B的子类,类B称为类A的父类,子类继承父类的属性与方法,父类也可以调用子类的属性与方法。
object是所有类的父类,也成为基类或超类。
在python中,继承的写法如下:
首先是单继承:
class A(object):
def func(self):
print("func1")
class B(A):
要让类B继承类A,只需要在类B的参数列表中写上A即可
例子如下:学生类继承Person类:
class Person(object):
def __init__(self,name,age,money):
self.name=name
self.age= age
self.__money=money
def setMoney(self,money):
#数据过滤
if money < 0:
money = 0
self.__money = money
def getMoney(self):
return self.__money
def run(self):
print("run")
def eat(self,food):
print("eat"+food)
from person import Person
class Student(Person):
def __init__(self,name,age,money,stuId):
super(Student,self).__init__(name,age,money)
#子类可以有一些自己独有的属性
self.stuId =stuId
def stuFunc(self):
print(self.__money)
from student import Student
stu = Student("tom",18,1000,110)
print(stu.name,stu.age)
stu.run()
print(stu.stuId)
# stu.stuFunc()
print(stu.getMoney())
通过子类可以调用父类的方法
在类中,__init__()代表构造函数:
class person(object):
# name =""
# age =18
# height = 0
# weight = 0
#定义方法(定义函数)
def run(self):
print("run")
def eat(self,food):
print("eat " +food)
def __init__(self,name,age,height,wight):
# print(name,age,height,wight)
self.name = name
self.age= age
self.height = height
self.weight =wight
'''
构造函数:_init_()
在使用类创建对象的时候自动调用,如果不显示写出,默认自动添加空的构造函数
'''
per = person("李雷", 22, 177, 70)
print(per.name,per.age)
per1 = person("韩梅梅",20,170,50 )
print(per1.name,per1.age)
多继承:在参数列表中枚举所有父类:
class Father(object):#父亲类
def __init__(self,money):
self.money=money
def play(self):
print("play")
def func(self):
print("func1")
class Mother(object):#母亲类
def __init__(self,faceValue):
self.faceValue=faceValue
def eat(self):
print("eat")
def func(self):
print("func2")
from father import Father
from mother import Mother
class Child(Father,Mother):#儿子类
def __init__(self,money,faceValue):
#写法
Father.__init__(self,money)
Mother.__init__(self,faceValue)
from child import Child
def main():
c =Child(300,100)
print(c.money,c.faceValue)
c.play()
c.eat()
#注意:父类中方法名相同,默认调用的是写在前面的父类方法
if __name__ =="__mian__":
main()