Basic Analysis of Python Object-Oriented Programming (2), python Object-Oriented Programming

Source: Internet
Author: User
Tags types of functions

Basic Analysis of Python Object-Oriented Programming (2), python Object-Oriented Programming

Python has been quite popular recently, and it is even more popular than Luhan zhiqian, of course between programmers. Next, let's take a look at Python-related content.

In the previous article, we have introduced some basic knowledge about Python object-oriented programming. For details, refer to: Python Object-Oriented Programming BASICS (1). Next, let's take a look at another article.

Encapsulation

1. Why encapsulation?

Encapsulation is to hide the specific implementation details of data attributes and methods and only provide one interface. Encapsulation does not need to care about how objects are built. In fact, in object orientation, encapsulation is actually the most challenging level.

2. encapsulation includes data encapsulation and function encapsulation. Data encapsulation aims to protect privacy and function encapsulation aims to isolate complexity.

3. Data encapsulation is to add __

class People: 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)#19print(p.__salary)#AttributeError: 'People' object has no attribute '__salary'

Failed. An error is reported. Let's open the object namespace and see what happened.

print(p.__dict__)#{'name': 'zhang', 'age': 19, '_People__salary': 100000}

Oh, python has transformed _ salary into _ People _ salary.

print(p._People__salary)#100000

Therefore, Python is not absolutely hidden. As long as you know the above, it doesn't matter if you know it.
These deformation operations only occur in the class definition stage or the object definition (instantiation stage) stage.

Although the _ attribute cannot be directly accessed from the outside, it can be accessed within the class. It can be understood that in the definition phase, if the attribute starting with _ is met, the Python interpreter automatically identifies it as the _ class name_attribute, so it can be accessed within the class. In this way, we can do a little thing.

Let's first look at this

Class A: def foo (self): print ('from A foo') self. bar () def bar (self): print ('from A bar') class B (A): def bar (self): print ('from B bar ') B = B () B. foo () # from A foo # from B bar. When calling A function, do not look at the defined position.

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

Class A: def foo (self): print ('from A foo') self. _ bar () def _ bar (self): print ('from A bar') class B (A): def _ bar (self ): print ('from B bar') B = B () B. foo () # from A foo # Have you ever felt the beauty of programming in the from A bar?

4. encapsulated applications

1) We will not allow the outside world to see how our data attributes are defined. We can only see what we allow the outside world to see through the interfaces we provide.

class People: def __init__(self,name,age,height,weight,hobby):  self.__name=name  self.__age=age  self.__height=height  self.__weight=weight  self._hobby=hobby def tell_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) A more common scenario is that we can limit the data type and encapsulate the logic for users.

Def tell_name (self): print (self. _ name) # Change the name def set_name (self, new): if not isinstance (new, str): raise TypeError ('name must be string type') self. _ name = new

5. looking at the above operations, the user still needs p when viewing the name. tell_name () is a data attribute, but it is transformed into a function. How can we disguise it and use it?Property: the decorator.

class People: def __init__(self,name,age,height,weight,hobby):  self.__name=name  self.__age=age  self.__height=height  self.__weight=weight  self._hobby=hobby @property def name(self):  return self.__namep=People('zhang',18,1.90,75,'read')print(p.name)#zhang

Data attributes should also be modified and deleted

@ Property def name (self): return self. _ name # If the name has been modified by property, setter and deleter @ name are available. setter def name (self, new): if not isinstance (new, str): raise TypeError ('name must be string type') self. _ name = new @ name. deleter def name (self): del self. _ namep = People ('zhang ', 18, 1.90, 75, 'read') print (p. name) # zhangp. name = 'can '# modify print (p. name) # candel p. name # Delete print (p. name) # AttributeError: 'people' object has no attribute '_ People _ name'

1. Polymorphism

Although the concept of polymorphism is not mentioned yet, we have been using it. Polymorphism is the meaning of multiple forms. Animals are all cats, dogs, pigs, and so on. These are all forms of animals.

Reflected in Python, polymorphism means that the variable can be operated even if it does not know the object type referenced by the variable. For example, if the sequence type has the calculated length method len (), then we get a sequence Type x. We don't need to know what Type x is, just need to know that it is a sequence type, then we can use len (x) to calculate the length of x. This is polymorphism,Python itself is a Polymorphism

Of course, we have learned a built-in function isinstance (), which can be used to determine the data type, but this does not conform to the beautiful characteristics of polymorphism.

2. Binding method and non-binding method

There are two types of functions defined in the class: binding method and non-binding method.

1) binding method

The binding method is divided into the method bound to the class and the method used to bind to the object.

Any method defined in the class and not modified by any decorator is bound to an object.

The feature is that obj. func () will automatically pass in obj as the first parameter, because the logic of func is to process obj.

The classmethod modifier defined in the class is the method bound to the class.

The feature is that cls. func () will automatically pass in the class cls as the first parameter, because the logic of func is to process cls.Even if an object calls this function, the class is passed in as the first parameter.

class People: def __init__(self,name):  self.name=name def bar(self):  print('----->',self.name) @classmethod def func(cls):  print(cls)p1=People('zhang')p1.func() #<class '__main__.People'>People.func()#<class '__main__.People'>

2) Non-binding method

Another method is not bound to a class or an object. It is called a non-binding method.

Decoration with staticmethod

# File name: pickle_testimport hashlibimport timeimport pickleimport osstudent_path = r 'C: \ Users \ Administrator \ PycharmProjects \ test \ student 'class People: def _ init _ (self, name, sex, user_id): self. name = name self. sex = sex self. user_id = user_id self. id = self. create_id () def tell_info (self): print (''' -------- % s info -------- id: % s name: % s sex: % s user_id: % s ''' % (self. name, self. id, self. name, self. sex, self. user_id) def create_id (self): m = hashlib. md5 () m. update (self. name. encode ('utf-8') m. update (self. sex. encode ('utf-8') m. update (str (self. user_id ). encode ('utf-8') return m. hexdigest () def save (self): with open (self. id, 'wb ') as f: pickle. dump (self, f) @ staticmethod # a non-binding method is a function. It is just a tool and does not require classes or objects def get_all (): res = OS. listdir (student_path) for item in res: file_path = r '% s \ % s' % (student_path, item) with open (file_path, 'rb') as f: obj = pickle. load (f) obj. tell_info () # deserialization. pyfrom pickle_test import Peoplep = People ('zhang ', 'male', 123123123) p. get_all ()

3. Software Development specifications

In the real software development process, not all code is written in one file. You can imagine that a small program has about 10000 lines of code written in one file, are you still doing this?

The correct method should be to split the program into one module. For example, you can put executable files in common bin directories and configuration files in conf directories.
Store data in the db directory, log files in the log directory, libraries in the lib directory, and some important code in the src directory, such as important logic and class definitions.

Summary

The above is all about the basic parsing of Python object-oriented programming. I hope it will be helpful to you. If you are interested, you can continue to refer to this site: details of the ModelForm code of Python exploration, and descriptions of how to solve the garbled problem in the content of requests crawling to the webpage in python. If you have any shortcomings, please leave a message. Thank you for your support!

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.