Python中类继承和方法重写的示例
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python中类继承和方法重写的示例相关的知识,希望对你有一定的参考价值。
This simple example will show you how to inherit a class from a parent class. I have to apologise for some grammar mistakes that I've probably put in the comments, but English is not my native language.If you execute this code, the output will be:
Here comes Lois Lane
Here comes Jimmy Olsen
Here comes Clark Kent
...but his secret identity is 'Superman' and he's a super-hero!
--> Let's see what a man can do:
Jimmy Olsen walks
Lois Lane says: 'Oh no, we're in danger!'
--> Let's see what a superman can do:
Clark Kent walks
Clark Kent says: 'This is a job for SUPERMAN!'
Superman run at the speed of light
Superman fly up in the sky
Superman uses his x-ray vision
#!/usr/bin/env python class man(object): # name of the man name = "" def __init__(self, P_name): """ Class constructor """ self.name = P_name print("Here comes " + self.name) def talk(self, P_message): print(self.name + " says: '" + P_message + "'") def walk(self): """ This let an instance of a man to walk """ print(self.name + " walks") # This class inherits from Man class # A superman has all the powers of a man (A.K.A. Methods and Properties in our case ;-) class superman(man): # Name of his secret identity secret_identity = "" def __init__(self, P_name, P_secret_identity): """ Class constructor that overrides its parent class constructor""" # Invokes the class constructor of the parent class # super(superman, self).__init__(P_name) # Now let's add a secret identity self.secret_identity = P_secret_identity print("...but his secret identity is '" + self.secret_identity + "' and he's a super-hero!") def walk(self, P_super_speed = False): # Overrides the normal walk, because a superman can walk at a normal # pace or run at the speed of light! if (not P_super_speed): super(superman, self).walk() else: print(self.secret_identity + " run at the speed of light") def fly(self): """ This let an instance of a superman to fly """ # No man can do this! print(self.secret_identity + " fly up in the sky") def x_ray(self): """ This let an instance of a superman to use his x-ray vision """ # No man can do this! print(self.secret_identity + " uses his x-ray vision") # Declare some instances of man and superman lois = man("Lois Lane") jimmy = man("Jimmy Olsen") clark = superman("Clark Kent", "Superman") # Let's puth them into action! print(" --> Let's see what a man can do: ") jimmy.walk() lois.talk("Oh no, we're in danger!") print(" --> Let's see what a superman can do: ") clark.walk() clark.talk("This is a job for SUPERMAN!") clark.walk(True) clark.fly() clark.x_ray()
以上是关于Python中类继承和方法重写的示例的主要内容,如果未能解决你的问题,请参考以下文章