Detailed description and code of Inheritance
InheritanceCode can be reused, which is the relationship between types and subtypes;
In Python, inheritance is to fill in the brackets of the class name with the inherited base class, that isClass DerivedClass (BaseClass ):
Base class initializationYou need to use the self variable, that isBaseClass. _ init _ (self, val1, val2), You need to manually call the base class constructor;
DerivedShareThe member variables of the base class can be directly used using self. val;
YesOverride)The method of the base class will give priority to the method of the derived class;
The Code is as follows::
#-*-Coding: UTF-8-*-# = # File: ClassExercise. py # Author: Wendy # Date: 2014-03-03 #============================#eclipse pydev, python2.7class Person: def _ init _ (self, name, age): self. name = name self. age = age print ('(Initialized Person: {0 })'. format (self. name) def tell (self): print ('name: {0} Age: {1 }'. format (self. name, self. age) class Man (Person): # inherit def _ init _ (self, name, age, salary): Person. _ init _ (self, name, age) self. salary = salary print ('(Initialized Man: {0 })'. format (self. name) def tell (self): # override the base class method Person. tell (self) print ('salary: {0: d }'. format (self. salary) class Woman (Person): def _ init _ (self, name, age, score): Person. _ init _ (self, name, age) self. score = score print ('(Initialized Woman: {0 })'. format (self. name) def tell (self): # override the base class method Person. tell (self) print ('score: {0: d }'. format (self. score) c = Woman ('caroline ', 30, 80) s = Man ('Spike', 25,150 00) print ('') members = [c, s] for m in members: m. tell ()
Output:
(Initialized Person: Caroline)(Initialized Woman: Caroline)(Initialized Person: Spike)(Initialized Man: Spike)Name:Caroline Age:30score: 80Name:Spike Age:25Salary: 15000