Python Object-Oriented Programming (1), python Object-Oriented Programming

Source: Internet
Author: User

Python Object-Oriented Programming (1), python Object-Oriented Programming

1. What is object-oriented

Object-oriented (oop) is an abstract method to understand the world. Everything in the world can be abstracted into an object. Everything is made up of objects. In programming, an application is a method for developing a program. It uses an object as the basic unit of the program.

2. Differences between object-oriented and process-oriented

We have already introduced process orientation.

Advantages: complicated problems are simplified and streamlined

Disadvantage: poor scalability

Main application scenarios include Linux kernel, git, and http Services.

The core of object-oriented programming is objects. objects are a combination of features (variables) and skills (functions.

Advantage: solved the problem of poor program scalability

Disadvantage: Poor controllability, unable to predict the final result

The main application scenario is the software with changing requirements, that is, the software that interacts frequently with users.

It should be noted that object-oriented programming cannot solve all the problems, but is only used to solve scalability. Of course, the current Internet software, scalability is the most important

3. Concepts of objects and Classes

In python, everything is an object. An object should have its own attributes, that is, features, and functions, that is, methods.

In Python, features are represented by variables and functions, so objects are a combination of variables and functions.

Classes are extracted from various objects that contain the same features and functions. Therefore, classes are a combination of common features and functions of a series of objects.

Let's define a class. The method is similar to defining a function:

# Define a Chinese class Chinese: # common features country = 'China' # common skills def talk (self): print ('is talking China ') def eat (self): print ('is eating Chinese food ')

In this way, we have defined a class. Note: 1. Define the class with the class keyword.

2. The class name is generally capitalized and does not need parentheses before the colon, which is different from the function definition.
3. Unlike functions, classes execute the code in the class at the definition stage.

4. A class has two types of attributes. Common features are called data attributes, and common functions are called function attributes.

How can this class generate an object? Instantiation:

# An object p1 = Chinese () is generated by instantiation ()
P2 = Chinese ()

We can draw a conclusion that no matter what happens in the real world, in the program, there is indeed a class, only available objects.

We have already obtained two objects by instantiating them. However, there is a problem that the features and functions of the two objects are the same. The concept of all objects is totally different, every object is different. This world is interesting.

In fact, when we define a class, we forget to define the _ init _ () function. The correct definition method should be like this:

# Define a Chinese class Chinese: # common features country = 'China' # initialize def _ init _ (self, name, age): self. name = name # each object has its own name self. age = age # each object has its own age # common skills def talk (self): print ('is talking Chinese') def eat (self ): print ('is eating Chinese food') # An object p1 = Chinese ('zhang ', 18) is generated by instantiation)

Class Name brackets are instantiation. instantiation will automatically trigger the _ init _ FUNCTION operation. You can use them to customize your own features for each object.

When we define the _ init _ function, there are three parameters in the brackets, but we passed only two values during the instantiation call. Why not report an error? This is because self is used to automatically pass the object itself to the first parameter of the _ init _ function during instantiation. Of course, self is just a name, the instructor egon says that a few blind times can't be understood by others.

Note. This automatic value transfer mechanism is only reflected during instantiation. In addition to instantiation, the class also has a function of attribute reference, and the method is class name.

# Print (Chinese. country) # China # reference class Function Attributes # Chinese. talk () # TypeError: talk () missing 1 required positional argument: 'Self 'print (Chinese. talk) # <function Chinese. talk at 0x000001BC5F13D1E0> Chinese. talk ('self ') # is talking Chinese # Add attribute Chinese. color = 'yellow' # Delete attribute del Chinese. color

The error code above shows that when the attribute is referenced, the value is not automatically transferred.

We have learned the concept of namespace, defining a variable, or defining a function will open up a memory space in the memory, and there are also defined variables (data attributes) in the class ), define functions (function attributes). They also have namespaces. _ dict _

p1=Chinese('zhang',18)print(Chinese.__dict__)#{'__module__': '__main__', 'country': 'China', '__init__': <function Chinese.__# init__ at 0x000002187F35D158>, 'talk': <function Chinese.talk at 0x000002187F35D1E0>, # 'eat': <function Chinese.eat at 0x000002187F35D268>, '__# dict__': <attribute '__dict__' of 'Chinese' objects>,#  '__weakref__': <attribute '__weakref__' of 'Chinese' objects>, '__doc__': None}print(p1.__dict__)#{'name': 'zhang', 'age': 18}

We can see through the results shown in the code above. Print the namespace of the instantiated object and only display its own attributes. If you want to find the attributes that are common to other objects, go to the namespace of the class.

Another problem is that there is no function attribute in the object namespace. Of course, it is also found in the class. But is the function specified by different objects a function?

p1=Chinese('zhang',18)p2=Chinese('li',19)print(Chinese.talk)#<function Chinese.talk at 0x000001B8A5B7D1E0>print(p1.talk)     #<bound method Chinese.talk of <__main__.Chinese object at 0x000001B8A5B7BD68>>print(p2.talk)     #<bound method Chinese.talk of <__main__.Chinese object at 0x000001B8A5B7BDA0>>

As you can see, no, their memory addresses are different. Note that bound method is the binding method.

The object itself only has data attributes, but the Python class mechanism binds class functions to objects, called object methods or binding methods. The binding method binds only one object, and the methods of the same class are bound to different objects, which belong to different methods. We can verify that:

When this function is used: the class calls the function attribute. Since it is a function, it is a function name with brackets, and there are parameter data transmission parameters.

When an object uses this function, the object does not have a function attribute. It is a binding method. How can we use the binding method? It also directly adds brackets, but the difference is, the binding method uses the object as the first parameter by default.

class Chinese:    country='China'    def __init__(self,name,age):        self.name=name          self.age=age        def talk(self):        print('%s is talking Chinese'%self.name)    def eat(self):        print('is eating Chinese food')p1=Chinese('zhang',18)p2=Chinese('li',19)Chinese.talk(p1)    #zhang is talking Chinesep1.talk()           #zhang is talking Chinese

As long as it is a binding method, it will automatically pass the value! In fact, we have been familiar with this before. In python3, the type is a class. Data types such as list, tuple, set, and dict are actually classes. We used methods such as l1.append (3) and can also write: l1.append (l1, 3)

Not complete...

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.