Python Basic----Encapsulation

Source: Internet
Author: User

From the meaning of the package itself to understand, the package is like a sack, the kitten, puppy, Xiao Wang eight, as well as Egon and Alex into the sack, and then seal the sack. But in fact this kind of understanding is rather partial

First we need to understand

What to encapsulate

How much money do you have in your wallet (data encapsulation)

Your sexual orientation (the encapsulation of data)

How do you pee? How the specific function is implemented (encapsulation of the method)

Why to encapsulate

The main reason for encapsulating data is: Protecting privacy (as a man, you have a face that says: I like men, are you scared?) )

The main reason for encapsulation is: isolation complexity (the shutter is the method shoot camera provides for fools, which hides the complex photographic functions of the interior, for example, you don't have to know how your own urine is going to flow out of the way, You can use the urine function directly by pulling out your own interface.

There is no one in your body that does not embody the concept of encapsulation: your body hides the bladder, the urethra, and so on, and then provides you with an interface to the urine (the interface is yours ...). , you can't just hang your bladder outside your body and show off when you're on the toilet: Hi,man, look at my bladder and see how I pee. And your head wraps your brain into the skull, and then provides the eye with this interface ....

Hint: In the programming language, the externally provided interface (interface can be understood for a portal), is a function, called an interface function, which is not the same as the concept of an interface, the interface represents a set of interface functions of the body.

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 the portal, with this portal, the user does not have to directly access to the internal hidden details, can only walk the interface, and we can attach more processing logic on the implementation of the interface , thus strictly controlling the user's 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 to access the name inside, which in itself is a package

>>> r1.nickname ' Bush lun '>>> riven.camp'  Noxus'

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

The second layer of encapsulation: the class hides certain properties and methods (or defines them as private), is used only inside the class, is inaccessible externally, or leaves a small number of interfaces (functions) for external access.

Implement hidden properties (set to private) in Python with double underlines

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

classA:__n=0#The data properties of the class should be shared, but syntactically it is possible to set the data property of the class to private, such as __n, to be transformed into _a__n    def __init__(self): self.__x=10#deformation to self._a__x    def __foo(self):#deformation to _a__foo        Print('From A')    defBar (self): self.__foo()#only within the class can you access it in the form of __foo.

Features of this automatic deformation:

1. Defined in the class __x can only be used internally, such as Self.__x, which is referred to as the result of deformation .

2. This deformation is in fact the external deformation , the outside is not accessible by the name __x.

3. The __x defined in the subclass does not overwrite the __x defined by the parent class, because the subclass is formed: The subclass name is __x, and the parent class is formed: The parent class name __x, that is, when the double-glide line begins with a property that inherits to the 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 inside it, and then externally it can use the

The problems to be aware of in this deformation are:

1. This mechanism also does not really restrict our direct access to properties from the outside, know the class name and property name can be spelled out name: _ Class Name __ property, then you can access, such as A._a__n

>>> a=A ()>>> a._a__n>>> a._a__x>>> a._a__n

2. The process of deformation occurs only once in the definition of the class, the assignment operation after the definition, does not deform

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

#Normal situation>>>classA: ...deffa (self): ...Print('From A')...     defTest (self): ... self.fa () ...>>>classB (A): ...deffa (self): ...Print('From B')... >>> b=B ()>>>b.test () fromB
#define FA as private, i.e. __fa>>>classA: ...def __fa(self):#deform to _A__FA when defined...Print('From A')...     defTest (self): ... self.__fa()#only the class that you are in will be called _a__fa... >>>classB (A): ...def __fa(self): ...Print('From B')... >>> b=B ()>>>b.test () fromA

Python does not really prevent you from accessing private properties, the module also follows this convention, if the module name starts with a single underscore, then the From module import * cannot be imported, but you from module import _private_ Module is still available for import

In fact, many times you go to invoke the function of a module will encounter a single underscore beginning (Socket._socket,sys._home,sys._clear_type_cache), these are private, in principle, for internal calls, as the outside of you, It can be used, but it seems a little bit silly

Python to be like other programming languages, strictly control the access rights of properties, only with the help of built-in methods such as __GETATTR__, see Object-oriented advanced.

Class notes:

classA:__x=1#_a__x    def __test(Self:#_a__test        Print('From A')PrintA.__x)Print(a._a__x) A=A ()Print(a._a__x)PrintA.__dict__)PrintA.__dict__) A._a__test (123) A=A () a._a__test ()#__ Name, this syntax, only when the definition of the effect of deformation, if the class or object has been produced, there will be no deformation effectclassB:PassB.__x=1PrintB.__dict__)PrintB.__x) b=B () b.__x=1Print(b.__dict__)Print(b.__x)#it will deform in the definition phase .classA:def __fa(self):#_a__fa        Print('From A')    defTest (self): self.__fa()#Self._a__faclassB (A):def __fa(self):#_b__fa        Print('From B') b=B () b.test ()classA:def __init__(self): self.__x=1defTell (self):Print(self.)__x)#self.__x can be used to access the deformed properties directly within the class by using the name __ .a=A ()Print(A.__dict__)Print(A.__x) A.tell ()
Notes

Encapsulation and extensibility

Encapsulation is a clear distinction between inside and outside, so that the class implementation can modify the contents of the package without affecting the external caller's code, while the external use of the user only know an interface (function), as long as the interface (function) name, parameters, the user's code will never need to change. This provides a good basis for cooperation--or, as long as the interface's underlying contract is unchanged, the code changes anthias.

#Designer of the classclass:def __init__(Self,name,owner,width,length,high): Self.name=name Self.owner=owner self.__width=width self.__length=length self.__high= HighdefTell_area (self):#externally provided interface that hides the internal implementation details, at this point we want to ask for an area        returnSelf.__width* Self.__length
# users >>> r1=room (' bedroom ','Egon', 20,20,20  )# User Call interface Tell_area400
#The designer of the class can easily extend the functionality, and the user of the class does not need to change their own code at allclass:def __init__(Self,name,owner,width,length,high): Self.name=name Self.owner=owner self.__width=width self.__length=length self.__high= HighdefTell_area (self):#externally provided interface, hidden internal implementation, at this time we want to ask for the volume, the internal logic has changed, only need to repair the following line can be very simple implementation, and external calls not aware, still use the method, but the function has changed        returnSelf.__width* Self.__length* Self.__high

For those who are still using the Tell_area interface, there is no need to change their code to use the new features

>>> R1.tell_area ()8000

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