Python Learning (vii) Object-oriented-inheritance and polymorphism

Source: Internet
Author: User

Python class inheritance and polymorphism

In OOP (Object oriented programming) programming, when we define a class, we can inherit from an existing class, a new class called a subclass (subclass), The inherited class is called the base class, the parent class, or the superclass (base class, Super Class).

Let's start by defining a class, named person, representing people, defining attribute variables name and sex (name and gender), and defining a method: When sex is male, print he; when sex is female, print she

Refer to the following code:

1 classPerson :2     def __init__(self,name,sex):3Self.name =name4Self.sex =Sex5         6     defPrint_heorshe (self):7         ifSelf.sex = ="male":8             Print("He")9         elifSelf.sex = ="female":Ten             Print("She") One  AMay = person (" May","female") -Peter = Person ("Peter","male") -  the May.print_heorshe () -Peter.print_heorshe ()

When we write the Student class, we can inherit the person class completely, and use class Subclass_name (Baseclass_name) to represent the inheritance;

What are the benefits of inheritance? The biggest benefit is that the subclass obtains the full functionality of the parent class. The Print_heorshe method of the parent class can be used directly as follows student class

When instantiating student, subclasses need to provide the two attribute variables required by the parent class name and sex

1 classPerson :2     def __init__(self,name,sex):3Self.name =name4Self.sex =Sex5         6     defPrint_heorshe (self):7         ifSelf.sex = ="male":8             Print("He")9         elifSelf.sex = ="female":Ten             Print("She") One  A classStudent (person):#Student inherit person -     Pass -  theMay = Student (" May","female") -Peter = Student ("Peter","male") -  - Print(May.name,may.sex,peter.name,peter.sex) + May.print_heorshe () -Peter.print_heorshe ()

Python Learning (vii) Object-oriented-inheritance and polymorphism

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.