Home  >  Article  >  Backend Development  >  Detailed introduction to Python object-oriented programming

Detailed introduction to Python object-oriented programming

零下一度
零下一度Original
2017-07-03 09:41:371396browse

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, and everything is composed of objects. Applied in programming, it is a method of developing programs that uses objects as the basic unit of the program.

2. The difference between object-oriented and process-oriented

We have introduced process-oriented before. The core of process-oriented is the word 'process'. Process is the steps to solve problems. Process-oriented The method of designing a program is like designing an assembly line, which is a mechanical way of thinking

Advantages: Complex problems are simplified and streamlined

Disadvantages: Poor scalability

Main application scenarios include: Linux kernel, git, and http service

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

Advantages: Solve the problem of poor program scalability

Disadvantages: Poor controllability, unable to predict the final result

The main application scenario is software with frequently changing needs, that is, with users Software that interacts frequently

It should be noted that object-oriented programming does not solve all problems, it is only used to solve scalability. Of course, in today's Internet software, scalability is the most important

3. The concept of objects and classes

In Python, everything is an object, and an object should have its own attributes, and It is a feature, and it also has its own function, that is, a method

In Python, features are represented by variables, and functions are represented by functions, so the object is a combination of variables and functions

And from each Classes are extracted from various objects with the same characteristics and functions, so a class is a combination of common characteristics and functions of a series of objects

Let us define a class, methods and Defining a function is somewhat similar:

#定义一个中国人的类class Chinese:#共同的特征country='China'#共同的技能def talk(self):print('is talking Chinese')def eat(self):print('is eating Chinese food')

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

to define a class. 2. The class name usually begins with The letters are capitalized, and no parentheses are needed before the colon, which is different from function definition
     3. Different from functions, classes will execute the code in the class during the definition phase

      4. Classes have two attributes, common The characteristics are called data attributes, and the common functions are called function attributes.

How to generate an object from this class? Instantiation:

p1=Chinese()
p2=Chinese()

We can conclude that no matter what happens in the real world, in a program, there is indeed a class first, and then there are objects

We have obtained two objects through instantiation, but there is a problem. The characteristics and functions of the two objects are the same. This is completely inconsistent with the concept that everything is an object. Every object should be It's different. Only such a world is interesting.

In fact, when we defined the class, we forgot to define the __init__() function. The correct definition method should be like this:

#定义一个中国人的类class Chinese:#共同的特征country='China'#初始化def __init__(self,name,age):
        self.name=name  #每个对象都有自己的名字self.age=age    #每个对象都有自己的年龄#共同的技能def talk(self):print('is talking Chinese')def eat(self):print('is eating Chinese food')#实例化的方式产生一个对象p1=Chinese('zhang',18)

The class name with parentheses is instantiation. Instantiation will automatically trigger the __init__ function to run. You can use it to customize your own characteristics for each object.

We are defining __init_ _function, there are three parameters in the parentheses, but when we instantiate the call, we only pass two values. Why is it not reporting an error? This is because the function of self is to automatically pass the object itself to the first parameter of the __init__ function when instantiating it. Of course, self is just a name. Teacher egon said that if you write it blindly, others will not be able to understand it.

Notice. This automatic value transfer mechanism is only reflected when instantiating. In addition to instantiation, a class also has the function of attribute reference. The method is the class name. Attribute

#引用类的数据属性print(Chinese.country)  #China#引用类的函数属性# Chinese.talk()#TypeError: talk() missing 1 required positional argument: 'self'print(Chinese.talk) #<function Chinese.talk at 0x000001BC5F13D1E0>Chinese.talk('self')    #is talking Chinese#增加属性Chinese.color='yellow'#删除属性del Chinese.color

From above It can be seen from the error code that when an attribute is referenced, there is no automatic value transfer.

We have learned the concept of namespace. Defining a variable or defining a function will open up a memory space in the memory. There are also defined variables (data attributes) and defined functions (function attributes) in the class. They also have namespaces, which can be viewed through the .__dict__ method.

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 &#39;__dict__&#39; of &#39;Chinese&#39; objects>,#  '__weakref__': <attribute &#39;__weakref__&#39; of &#39;Chinese&#39; objects>, '__doc__': None}print(p1.__dict__)#{'name': 'zhang', 'age': 18}

We can see the results displayed through the above code Got it, print the namespace of the instantiated object, and only display its own unique attributes. If you want to find the attributes that are common to other objects, you have to go to the namespace of the class to find

There is another The problem is, there is no function attribute in the namespace of the object. Of course, I have to look for it in the class, but are the functions specified by different objects the same 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>>

可以看到,并不是,他们的内存地址都不一样。而且注意bound method,是绑定方法

对象本身只有数据属性,但是Python的class机制将类的函数也绑定到对象上,称为对象的方法,或者叫绑定方法。绑定方法唯一绑定一个对象,同一个类的方法绑定到不同的对象上,属于不同的方法。我们可以验证一下:

当用到这个函数时:类调用的是函数属性,既然是函数,就是函数名加括号,有参数传参数

而对象用到这个函数时,对象没有函数属性,他是绑定方法,绑定方法怎么用呢,也是直接加括号,但不同的是,绑定方法会默认把对象自己作为第一个参数

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

只要是绑定方法,就会自动传值!其实我们以前就接触过这个,在python3中,类型就是类。数据类型如list,tuple,set,dict这些,实际上也都是类,我们以前用的方法如l1.append(3),还可以这样写:l1.append(l1,3)

未完待续。。。

The above is the detailed content of Detailed introduction to Python object-oriented programming. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn