Detailed introduction to Python object-oriented programming

Source: Internet
Author: User
1. What is Object-oriented

Object-oriented (OOP) is an abstract way to understand the world, all things can be abstracted into an object, everything is composed of objects. Application in programming is a method of developing a program that uses an object as the basic unit of a program.

2. Object-oriented and process-oriented differences

We have already introduced the process-oriented, process-oriented core in the ' process ' word, the process is the steps to solve the problem, process-oriented method design program is like a pipeline, is a mechanical way of thinking

Advantages: Complex problems are simplified and streamlined

Cons: Poor scalability

The main application scenarios are: Linux kernel, git, and HTTP service

Object-oriented programming, the core is the object, the object is a combination of features (variables) and skills (functions).

Advantages: Solve the problem of poor program extensibility

Cons: Poor controllability, inability to predict final results

The main application scenario is the software with frequently changing requirements, that is, the software that interacts with the user more frequently

It is important to note that object-oriented programming does not solve all the problems, but only to solve the extensibility. Of course, now the Internet software, extensibility is the most important

3. Concepts of objects and classes

In Python, everything is object, an object should have its own attributes, that is, features, and has its own function, that is, the method

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

And from a variety of objects extracted with the same characteristics and the same function is composed of the class, so the class is a series of objects common features and functions of the combination of the body

Let's define a class in a way that is somewhat similar to defining a function:

#定义一个中国人的类class Chinese: #共同的特征country = "China" #共同的技能def Talk (self):p rint (' was Talking Chinese ') def eat (self):p rint (' Is eating Chinese food ')

So we've defined a class, note: 1. Defining classes with Class keywords

2. The class name is generally capitalized, and the colon does not need parentheses before it, as distinct from the function definition
3. Unlike functions, classes execute code inside classes during the definition phase

4. The class has two properties, the common characteristic is called the data attribute, the common function is called the function attribute

How do you create an object from this class? Instantiation:

P1=chinese () P2=chinese ()

We can come to the conclusion that no matter what the real world is like, but in the program, it is really the first class, only the object

We have been instantiated by the way to get two objects, but there is a problem, get two objects, features and functions are the same, this is the object of all objects of the idea completely inconsistent Ah, should be every object is different, so the world is interesting AH

In fact, when we define a class, we forget to define __INIT__ (), and the correct definition method should be:

#定义一个中国人的类class Chinese: #共同的特征country = ' China ' #初始化def __init__ (self,name,age):        self.name=name  # Each object has its own name Self.age=age    #每个对象都有自己的年龄 # Common skills def talk (self):p rint (' was Talking Chinese ') def eat (self):p rint (' is Eating Chinese food ') #实例化的方式产生一个对象p1 =chinese (' Zhang ', 18)

The parentheses of the class name are instantiated, and the instantiation automatically triggers the __INIT__ function, which can be used to customize its own characteristics for each object.

When we define the __INIT__ function, there are three parameters in parentheses, but when we instantiate the call we only pass two values, why not error? This is because the role of self is: when instantiated, the object itself is automatically passed to the first parameter of the __INIT__ function, of course, it is only a name, Egon teacher said blind a few to write others can not understand.

Attention. This automatic value-passing mechanism only manifests when instantiated, and the class has a role in addition to instantiation as a property reference, and the method is the class name. property

#引用类的数据属性print (chinese.country)  #China # Function Properties of a reference Class # Chinese.talk () #TypeError: Talk () missing 1 required positional Argument: ' Self ' print (chinese.talk) #<function chinese.talk @ 0x000001bc5f13d1e0>chinese.talk (' self ')    # Is talking chinese# Add property chinese.color= ' Yellow ' #删除属性del chinese.color

From the above error code can be seen, the property reference time, there is no automatic value of the matter

We learned the concept of namespaces, defined a variable, or defined a function that would open up a memory space in memory, a class that also defines variables (data attributes), defined functions (function attributes), and they also have namespaces that can be viewed through the. __dict__ method.

P1=chinese (' Zhang ') print (chinese.__dict__) #{' __module__ ': ' __main__ ', ' country ': ' China ', ' __init__ ': < function chinese.__# init__ at 0x000002187f35d158> "Talk": <function Chinese.talk at 0x000002187f35d1e0>, # ' EA T ': <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}

As shown in the above code, we know that the namespace of the instantiated object is printed, only its own properties are displayed, and if you want to find properties that are common to other objects, go to the namespace of the class to find

Another problem is that there is no function attribute in the namespace of the object, and of course it is going to be found in the class, but the function specified by the different object is a function

P1=chinese (' Zhang ') p2=chinese (' Li ', p) 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, not all of their memory addresses are different. And note that bound method is the binding approach

The object itself has only data properties, but the Python class mechanism binds the function of the class to the object, called the object's method, or is called a binding method. A binding method uniquely binds an object, and a method of the same class is bound to a different object, and it belongs to a different method. We can verify that:

When this function is used: the class invokes the function attribute, since it is a function, it is the function name parentheses, parameter arguments

When the object uses this function, the object does not have a function attribute, he is the binding method, how to use the binding method, but also the direct parentheses, but the difference is that the binding method will default to the object itself as the first parameter

Class Chinese:    country= ' China ' def __init__ (self,name,age):        self.name=name          self.age=age    def talk ( Self):p rint ('%s are talking Chinese '%self.name) def eat (self):p rint (' was eating Chinese food ') P1=chinese (' Zhang ') p2= Chinese (' Li ', +) Chinese.talk (p1)    #zhang is Talking Chinesep1.talk ()           #zhang is talking Chinese

As long as the binding method, it will automatically pass the value! In fact, we have been exposed to this before, in Python3, the type is the class. Data types such as list,tuple,set,dict, are actually classes, we used methods such as L1.append (3), you can also write: L1.append (l1,3)

Not to be continued ...

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.