Python Polymorphism and encapsulation

Source: Internet
Author: User

What is polymorphic?

Polymorphism refers to the presence of multiple states in a class, implemented through inheritance.

Performance in Java: In a parameter you need to specify the data type, if this place can receive more than two types of parameters, then these types should have a parent class, the parent class is the type of all child class objects.

Polymorphic Forms of Expression:
def Pass def Pass def Pass

In Python, the parameters of a function do not need to specify a data type, so it is not necessary to unify the type of a set of classes through inheritance. In other words, all objects are actually type object, so in Python it's actually polymorphic. That

def func (a):   #  where a can either pass a cat or pass a dog type, casually pass any type. 
Duck Type:
def#  str list tuple dict set range ()print()  #  All the objects are duck type

It is not explicit that the polymorphism is implemented by inheritance, but it is determined by a vague concept that the function can receive this type of argument.

Packaging

What is encapsulation? Encapsulation can be divided into two kinds: narrow-sense encapsulation and generalized encapsulation .

Encapsulation in the broadest sense:

The encapsulation in the broadest sense is to encapsulate the code written in a container, in the form of:

class class Name:     def Method 1 (self):pass

The class defined above is intended only for objects in this class to use the definition to put methods in the class.

In the narrow sense of encapsulation:

In the narrow sense of encapsulation: the main is to hide a name in the class.

class Goods:     __discount = 0  #  private static variable    print(__discount) Goods ()   #  inside the class, it is possible to print out the private static variable print(Goods.  __discount)  #  attributeerror:type object ' Goods ' has no attribute ' __discount '

As you can see from the example above, a private static variable can be printed inside the class, but outside of the class you cannot reference a private static variable .

Static variables and method names in a class are executed during the process of loading and do not need to wait for a call.

Before this class is loaded, the name goods is not in the memory space.

A private static property can be used inside a class to hide the value of a variable.

View the form of static variables hidden inside a class:

class Goods:     __discount = 0print(Goods.  __dict__)    #  ' _goods__discount ': 0

By finding, the existence of a private static variable inside the class exists in the form of ' _ ' single underline , i.e.: _goods__discount. If the external call uses Goods._goods__discount to output what effect, try:

class Goods:     __discount = 0print(goods._goods__discount)    #  0

It is found that we can output private static variables. In terms of programming specifications, we cannot use private variables outside of the class .

We also have a preliminary understanding of the private variables, so why should we define a private variable?

1 First, you do not want the user to see the private variables;

2 second, do not want users to arbitrarily modify the private variables;

3 Again, if you can modify, you want users to modify the private variables have some restrictions , the purpose is to protect the security of data;

4 Finally, some methods and properties do not want the quilt class to be called .

Classification of private members in a class

1 private static properties # such as Properties in class: __discount = 0

2 Private Object Properties # as in __init__: Self.__name

3 Private Method # as defined in class Def __func (self):

Private Object Properties

1 classStudent:2     def __init__(self,name):3Self.__name=name4Colin = Student ('Colin')5 Print(Colin.name)#attributeerror: ' Student ' object has no attribute ' name '6 Print(Colin.__name)#attributeerror: ' Student ' object has no attribute ' __name '
1 classStudent:2     def __init__(self,name):3Self.__name=name4 5     defName (self):#to print class object properties by calling the class method6         returnSelf.__name7Colin = Student ('Colin')8 Print(Colin.name ())#Colin

Product Discount Example:

1 classGoods:2     __discount= 0.7#private static Property3     def __init__(self,name,price):4Self.name =name5Self.__price= Price#hide the price of a product6 @property7     defPrice (self):8         returnSelf.__price* Goods.__discount9 TenApple = Goods ('APPLE', 5) One Print(Apple.price)#3.5

Upgrade (Modify class object private properties):

1 classGoods:2     __discount= 0.7#private static Property3     def __init__(self,name,price):4Self.name =name5Self.__price= Price#hide the price of a product6 @property7     defPrice (self):8         returnSelf.__price* Goods.__discount9     defChange_price (self,new_price):Ten         ifType (New_price) isint: OneSelf.__price= New_price#Modifying Object Properties A         Else: -             Print('This price change is unsuccessful') -  theApple = Goods ('APPLE', 5) - Print(Apple.price)#3.5 -Apple.change_price (10) - Print(Apple.price)#7 +Apple.change_price ('dfred') - Print(Apple.price)

As we have described earlier, when a class private property is deformed inside a class, can the class of private variables be inherited? Give an example first:

1 classA:2     __country=' China'3     Print(__country)4 PrintA.__dict__)#Where: Class private properties are displayed in: _a__country mode storage5A.__language='Chinese'  #__language ': ' Chinese '6 PrintA.__dict__)7 PrintA.__language)
 1  class   A:  2  __country  =  " china   " 3  4  class       B (A):  5  print    (__country ) #   Nameerror:name ' _b__country ' is not defined  
1 class A: 2     __country '  China ' 3 4 class B (A): 5     Print (a._a__country)    #  China
Decorator (property)

property is an adorner function in Python, and how are all adorner functions used?

In the function, method, the top row of the class directly with the name of the @+ adorner .

The classification of adorners: can be divided into three kinds:1. Decoration function 2. Decoration Method (property) 3. Decoration Class .

Adorner method:

1 #Example 1:2 classStudent:3     def __init__(self,name):4Self.__name=name5 @property6     defName (self):#to print class object properties by calling the class method7         returnSelf.__name8Colin = Student ('Colin')9 Print(Colin.name)#Colin
1 #Example 2:2  fromMathImportPi3 classCircle:4     def __init__(self,r):5SELF.R =R6 @property7     defArea (self):8         returnSELF.R * * 2 *Pi9 @propertyTen     defperimeter (self): One         return2 * SELF.R *Pi AC1 = Circle (10) - Print(C1.area)#314.1592653589793 - Print(C1.perimeter)#62.83185307179586

Python Polymorphism and encapsulation

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.