Python-explanation and code of Inheritance

Source: Internet
Author: User

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


 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.