Python Object-oriented programming (bottom)

Source: Internet
Author: User

In this paper, we mainly introduce the encapsulation, inheritance and polymorphism of Python object-oriented programming by several examples.

Encapsulation of

Let's take a look at the example above, use the Student class to create an object, and modify the object's properties. The code is as follows:

#-*-coding:utf-8-*-#the creation of a classclassStudent (object):def __init__(self, Name, age): Self.name=name Self.age= Ageif __name__=='__main__': STU1= Student ('Zhangsan', 18) Stu1.age=-1PrintStu1.age

The Stu1 object's age property value is successfully modified to-1 in the instance, which is not a problem in the program. But in real life is unreasonable. Therefore, in the design of student class, we need to make some restrictions on the age and Name attribute, and do not allow the outside access. This requires the encapsulation of the implementation class.

Encapsulation of a class is the privatization of a property in a class when a class is defined, and the private property can only be accessed in the class in which it resides. To allow external access to private properties, you can set up a common interface to get or modify property values. We implement the encapsulation of the student class by modifying the code. The modified code is as follows:

#-*-coding:utf-8-*-#the creation of a classclassStudent (object):def __init__(self): self.__name=""Self .__age=0defsetName (self, name): Self.__name=namedefSetage (self, age):if(Age >0): Self.__age= AgeElse:            Print "Input Age Invalid"            defGetName (self):returnSelf.__name            defgetage (self):returnSelf.__age        if __name__=='__main__': STU1=Student () stu1.setname ("Zhangsan") Stu1.setage (-1)    Print "stu1.getname () =%s"%(Stu1.getname (),)Print "stu1.getage () =%d"% (Stu1.getage (),)

Code Description:

(1) Name, age defines an instance private attribute. Python does not have the same modifiers as private, procoted, public in Java to differentiate between instance private properties and instance common attributes. Instead, the flag is started with the existence of two underscores before the name of the property, and is represented as a private property if there is a double-down line. Conversely, it represents a public property.

(2) The SetName (), Setage () method is used to set the value of the property, and it is possible to add logic to the function to judge the input parameters. The GetName (), Getage () method is used as an external interface to get the value of the property. The encapsulation of attribute operations is implemented.

Inheritance of

inheritance is one of the important features of object-oriented. Inheritance allows you to create new classes that use or modify the behavior of existing classes. The original class is called a parent class or a superclass, and the new class is called a subclass or derived class. Inheritance enables the reuse of code. Python uses a pair of parentheses after the class name to represent the inherited relationship, and the class in parentheses is the parent class. If the parent class defines the __init__ method, the child class must display the __init__ method that invokes the parent class. If the subclass needs to extend the behavior of the parent class, you can add arguments to the __init__ method. The following code shows the implementation of the inheritance.

#-*-coding:utf-8-*-#the creation of a classclassFruit (object):def __init__(self, color):#__init__ as a constructor for a classSelf.color = Color#Instance Properties        Print "Fruit ' s color =%s"%(Self.color,)defGrow (self):Print "Fruit grow ()"classApple (Fruit):#inherit from fruit class    def __init__(self, color, name):#Constructors for subclassesFruit.__init__(Self, color)#to explicitly call the constructor of a parent class        Print "Apple ' s color =%s"%(Self.color,) Self.name= Name#New Properties        defSale (self):Print "Apple Sale ()" #overwrite the Grow method in the parent classclassBanana (Fruit):#inherit from fruit class    def __init__(self, color):#Constructors for subclassesFruit.__init__(Self, color)#to explicitly call the constructor of a parent class        defGrow (self):#New Method        Print "Banana grow ()"        if __name__=='__main__': Apple= Apple ('Red','Apple')#Apple.grow ()#inherits the Grow method of the parent class, which can be called directlyApple.sale () Banana= Banana ('Yellow') Banana.grow ()#

in the example, the Apple class automatically has the color attribute and the Grow () method by inheriting the fruit class. By inheriting, you can reduce the duplication of code.

Polymorphism

The inheritance mechanism illustrates that subclasses have public properties and methods of the parent class, and subclasses can extend their capabilities and add new properties and methods. As a result, subclasses can override the parent class object, which is known as polymorphism. Python's polymorphic nature is determined by the dynamic type of Python. Let's look at this section of code.

#-*-coding:utf-8-*-#the creation of a classclassFruit (object):def __init__(Self, Color=none):#__init__ as a constructor for a classSelf.color = Color#Instance Properties classApple (Fruit):#inherit from fruit class    def __init__(Self, color='Red'):#Constructors for subclassesFruit.__init__(Self, color)#to explicitly call the constructor of a parent classclassBanana (Fruit):#inherit from fruit class    def __init__(Self, color='Yellow'):#Constructors for subclassesFruit.__init__(Self, color)#to explicitly call the constructor of a parent class    classFruitshop (object):defsellfruit (self, fruit):ifisinstance (Fruit, Apple):Print "sell Apple"        ifisinstance (Fruit, Banana):Print "sell Apple"        ifisinstance (fruit, fruit):Print "Sell Fruit"            if __name__=='__main__': Shop=fruitshop () Apple=Apple () Banana=Banana () shop.sellfruit (apple) shop.sellfruit (Banana)

The output results are as follows:

Sell Applesell Fruitsell Applesell Fruit

The Sellfruit () method is defined in the Fruitshop class, which provides the parameter fruit. Sellfruit () returns different results depending on the type of fruit. Implementation results are implemented in a different invocation mode. This is polymorphism. By using polymorphism, you can increase the flexibility and scalability of your program.

Python Object-oriented programming (bottom)

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.