


Detailed introduction to 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, 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 '__dict__' of 'Chinese' objects>,# '__weakref__': <attribute '__weakref__' of 'Chinese' 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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

VS Code is the full name Visual Studio Code, which is a free and open source cross-platform code editor and development environment developed by Microsoft. It supports a wide range of programming languages and provides syntax highlighting, code automatic completion, code snippets and smart prompts to improve development efficiency. Through a rich extension ecosystem, users can add extensions to specific needs and languages, such as debuggers, code formatting tools, and Git integrations. VS Code also includes an intuitive debugger that helps quickly find and resolve bugs in your code.

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

VS Code not only can run Python, but also provides powerful functions, including: automatically identifying Python files after installing Python extensions, providing functions such as code completion, syntax highlighting, and debugging. Relying on the installed Python environment, extensions act as bridge connection editing and Python environment. The debugging functions include setting breakpoints, step-by-step debugging, viewing variable values, and improving debugging efficiency. The integrated terminal supports running complex commands such as unit testing and package management. Supports extended configuration and enhances features such as code formatting, analysis and version control.

Yes, VS Code can run Python code. To run Python efficiently in VS Code, complete the following steps: Install the Python interpreter and configure environment variables. Install the Python extension in VS Code. Run Python code in VS Code's terminal via the command line. Use VS Code's debugging capabilities and code formatting to improve development efficiency. Adopt good programming habits and use performance analysis tools to optimize code performance.
