Python Object-oriented programming (III)

Source: Internet
Author: User

Packaging

1. Why encapsulation?

Encapsulation is to hide the specifics of the details of the data properties and methods, providing only one interface. Encapsulation can be used without caring about how the object is built

2. Encapsulation includes the encapsulation of the data and the encapsulation of the function, the encapsulation of the data is to protect the privacy, the encapsulation of the function is to isolate the complexity

3. The encapsulation of the data is to precede the attribute with a __

classpeople:def __init__(self,name,age,salary): Self.name=name Self.age=Age self .__salary=Salaryp=people ('Zhang', 19,100000)Print(P.name)#ZhangPrint(P.age)# +Print(p.__salary)#attributeerror: ' People ' object has no attribute ' __salary '

Hey, error, let's open the object's namespace and see what happened.

Print (p.__dict__) # {' name ': ' Zhang ', ' age ': +, ' _people__salary ': 100000}

Oh, it turns out that Python changed __salary into _people__salary, and then again.

Print (p._people__salary) # 100000

So, Python is not absolutely hidden, as long as you know the above, it does not matter hidden

These deform operations occur only during the definition phase of the class or the object definition (instantiation phase) stage

Although there is no direct access to the properties of the __, but within the class can be accessed, you can understand that, in the definition phase, as long as the beginning of the Python interpreter is recognized as the _ Class name __ property, so within the class is accessible, so we can do a little bit of things

Look at this first.

classA:deffoo (self):Print('From A foo') Self.bar ()defBar (self):Print('From A Bar')classB (A):defBar (self):Print('From B Bar') b=B () b.foo () #from A foo
# From B Bar  do not think much of the call function when the definition of position, to see the call location

What if you want to call the bar () function of the parent class? How to do it

classA:deffoo (self):Print('From A foo') self.__bar()    def __bar(self):Print('From A Bar')classB (A):def __bar(self):Print('From B Bar') b=B () B.foo ()#From A foo        #Does the from A Bar feel programmed to enjoy

4. Application of the package

1) do not let the outside world see how our data attributes are defined, only through the interfaces we provide, to see what we allow the outside world to see

classpeople:def __init__(self,name,age,height,weight,hobby): Self.__name=name self.__age=Age self .__height=height self.__weight=Weight Self._hobby=HobbydefTell_info (self):Print(" "name:%s age:%s height:%s weeight:%s" "% (self.__name, self.__age, self.__height, self.__weight)) P=people ('Zhang', 18,1.90,75,'Read') P.tell_info ()

2) The more common scenario is that we can limit the type of data, add our own logic and then encapsulate it to the user

    def Tell_name (self):         Print (self.) __name )    # Modify name    def  Set_name (self,new):        if  not isinstance (NEW,STR):             Raise TypeError (' name must be string type ') self        . __name=new

5. Look at the above operation, the user to view the name of the time also have to P.tell_name (), is a data property, but we made it into a function, how to disguise it, you can use the property of the built-in function

classpeople:def __init__(self,name,age,height,weight,hobby): Self.__name=name self.__age=Age self .__height=height self.__weight=Weight Self._hobby=Hobby @propertydefname (self):returnSelf.__nameP=people ('Zhang', 18,1.90,75,'Read')Print(p.name) #zhang

Data properties should also have modifications, delete operations

@propertydefname (self):returnSelf.__name    #name has been modified by the property, there are setters and deleter@name. Setterdefname (self,new):if  notisinstance (NEW,STR):RaiseTypeError ('name must be a string type') self.__name=new @name. Deleterdefname (self):delSelf.__nameP= People ('Zhang', 18, 1.90, 75,'Read')Print(P.name)#ZhangP.name='can'    #ModifyPrint(P.name)#candelP.name#DeletePrint(P.name)#attributeerror: ' People ' object has no attribute ' _people__name '

Python Object-oriented programming (III)

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.