python学习笔记(十二) 面向对象之继承

      继承是类与类之间的关系,当类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()

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值