继承与多态(python)

面向过程的编程(OOP)中,当我们定义一个类(class)时,可以从某个现有的class继承,新的class成为子类(Subclass),被继承的class被称为基类、父类或者超类(Base class、Super class)。

>>> class Student(object):
	def study(self):
		print('Student is studying!')

>>> class Boy(Student):
	pass
>>> class Girl(Student):
	pass

>>> Tom = Boy()
>>> Tom.study()
Student is studying!

Boy,Girl是Student的子类,Student是Boy,Girl的父类,这就是继承,继承的好处是子类可以获得父类的全部功能。如上例中Boy子类自动拥有了父类Student父类的study()方法。

>>> class Boy(Student):
	def study(self):
		print('Boy is studying!')
	def eat(self):
		print('Boy is eating meet!')

		
>>> Tom = Boy()
>>> Tom.study
<bound method Boy.study of <__main__.Boy object at 0x022BD650>>
>>> Tom.study()
Boy is studying!
>>> Bot().study()

如上例所示,若我们对子类的方法进行定义,对Boy子类定义与父类相同的方法study(),子类中的方法将覆盖父类中的方法,在代码运行时,总会调用子类中的方法,这就是所谓的多态。

>>> class Man(Student):
	def study(self):
		print('Man is studying!')

		
>>> study_twice(Man())
Man is studying!
Man is studying!

定义Student父类中的一个子类,将新子类传入以父类作为参数的函数,均可以被调用。

静态语言VS动态语言

对于静态语言(如Java),若需要调用父类的方法,传入的对象必须是父类及它的子类;

对于动态语言,不一定需要传入父类及它的子类,只需要保证传入的对象中包含父类的方法,例如:

>>> class Woman(object):
	def study(self):
		print('Woman is not studying!')

		
>>> study_twice(Woman())
Woman is not studying!
Woman is not studying!

猜你喜欢

转载自blog.csdn.net/qq_42020470/article/details/81107406