Python-based encapsulation

Source: Internet
Author: User

First, what is the package

In programming, encapsulation (encapsulation) is an abstraction of a specific object, which is hidden from the outside of the program,

Meaning that other programs cannot be called.

To understand encapsulation, it is necessary to "privatize", that is, to restrict certain properties in a class or function to an area that cannot be called externally.

Second, why to encapsulate

The main reason for encapsulating data is to protect privacy (wrap up things you don't want to know about)

The main reason for encapsulation method is: Isolation complexity (for example: TV, we see is a black box, in fact, there are many electrical components, for

Users, we do not need to know that there are some components, television sets of those electrical components in the black box, provided to the user is just a few button interface,

The operation of the TV can be realized by the button. )

  Tip: In programming languages, externally provided interfaces (interfaces can be understood for a portal), functions, called interface functions, and the concept of interfaces

Not the same, the interface represents the collection body of a set of interface functions.

Three, the package is divided into two levels

Encapsulation is actually divided into two levels, but regardless of the level of encapsulation, to the outside world to provide good access to your internal hidden content interface (interface can be understood as

Port, with this portal, the user does not have to directly access the hidden details inside, only the interface, and we can attach more to the implementation of the interface

More processing logic to strictly control user access)

First-level encapsulation (nothing to do): Creating classes and objects creates namespaces for both, and we can only use the class name. or obj. Way to

Access the name inside, which is itself a package.

Print (M1.brand) #实例化对象 (M1.) print (Motor_vehicle.tag) #类名 (motor_vehicle.)-------------output--------------Spring Breeze Fuel Oil

  Note: For this level of encapsulation (hidden), the class name and the instance name. Is the interface that accesses the hidden property

  The second level of encapsulation: a class that hides certain properties and methods (or is defined as private), is used only within the class, cannot be accessed externally, or

The user leaves a small number of interfaces (functions) for external access.

The method of privatization in Python is also relatively straightforward, with two underscores in front of the properties that prepare the privatization, including the method, data.

Names that begin with all double underscores in a class, such as __x, are automatically formed: _ Class name __x form:

Class A:    __n=0 #类的数据属性就应该是共享的, but it is syntactically possible to set the data property of a class to private, such as __n, to _a__n    def __init__ (self):        self.__x=10 # Variant self._a__x    def __foo (self): #变形为_A__foo        print ("from A")    def Bar (self):        Self.__foo () #只有在类内部才可以通过 __foo in the form of access.

Features of this automatic deformation:

1, the __x defined in the class can only be used internally, such as self.__x, the result of the transformation is referred to.

2, this kind of deformation is in fact for the external deformation, in the outside can not be accessed through the name __x.

3, the __x defined in the subclass will not overwrite the __x defined by the parent class, because the subclass is formed: The subclass name __x, and the parent class becomes: _ Parent

Class name __x, where a property that begins with a double slide line is inherited to a subclass, the subclass cannot be overwritten.

Note: For this layer of encapsulation (hidden), we need to define a function (interface function) within the class to access the hidden property within it, and then

It can be used externally.

The problems to be aware of in this deformation are:

1, this mechanism also does not really restrict us from the external direct access to properties, know the class name and property name can spell name: _ Class name __ Genus

And then you can access it, such as A._a__n

A = A () print (a._a__n) print (a._a__x) print (a._a__n)--------output--------0100

2, deformation of the process only in the definition of the class is to occur once, after the definition of the assignment operation, will not deform

A = A () #实例化对象aprint (a.__dict__) #打印变形的内容a. __y = #新增Y的值, when add __ does not deform print (a.__dict__) #打印变形的内容---------output----------{ ' _a__x ': 10}{' _a__x ': Ten, ' __y ': #发现后面的Y并没有变形

3. In inheritance, the parent class can define a method as private if it does not want the subclass to overwrite its own method.

Class A: #这是正常情况    def fa (self):        print (' from A ')    def Test (self):        Self.fa () class B (A):    def fa (self):        print ("from B") B = B () b.test ()--------output----------from B

Take a look at the case where FA is defined as private:

Class A: #把fa定义成私有的, __fa    def __fa: #在定义时就变形为_A__fa        print ("from A")    def Test (self):        Self.__fa ( #只会与自己所在的类为准, that is, call _a__faclass B (A):    def __fa (self): #b调用的是test, it's okay with this.        print ("from B") B = B () b.test ()------- Output---------from A

  

Python-based 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.