Polymorphic
Class has an inheritance relationship, and the subclass type can be transformed upward as a parent class type, if we derive Student and Teacher from person, and both write a WhoAmI () method:
class Person (object): def __init__ (self, Name, gender): self.name = name Self.gender = Gender WhoAmI(self): return ' I am a person, my name is%s '% Self.nameclass Student (person): def __init__ (self, name , gender, score): super (Student, self). __INIT__ (name, gender) Self.score = score def WhoAmI( Self): return ' I am a Student, my name was%s '% Self.nameclass Teacher (person): def __init__ (self, name, gender, Course): super (Teacher, self). __INIT__ (name, gender) Self.course = Course def WhoAmI(self ): return ' I am a Teacher, my name is%s '% Self.name
In a function, if we receive a variable x, the result can be printed correctly whether the x is a person , a Student , or a Teacher:
def who_am_i (x): print X.whoami () p = person (' Tim ', ' Male ') s = Student (' Bob ', ' Male ',) t = Teacher (' Alice ', ' Female ', ' 中文版 ') who_am_i (p) who_am_i (s) who_am_i (t)
Operation Result:
I am a person, my name is TimI am a Student, my name is Bobi am a Teacher, my name is Alice
This behavior is known as polymorphism. In other words, the method invocation will work on the actual type of x . s is the Student type, which actually has its own WhoAmI () method and the WhoAmI method inherited from person, but calls S.whoami () Always look for its own definition first, and if not, look up the inheritance chain until it is found in a parent class.
Because Python is a dynamic language, the parameter x passed to the function who_am_i (x) is not necessarily a subtype of person or person. An instance of any data type can, as long as it has a whoami () method:
Class Book (object): def WhoAmI (self): return ' I am a book '
This is one of the biggest differences between dynamic and static languages, such as Java. A dynamic language invokes an instance method, does not check the type, and can be called as long as the method exists and the parameter is correct.
Source: http://www.imooc.com/code/6247
Polymorphic This is one of the biggest differences between dynamic and static languages, such as Java. A dynamic language invokes an instance method, does not check the type, and can be called as long as the method exists and the parameter is correct.