search
HomeBackend DevelopmentPython TutorialDetailed 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('self')    #is talking Chinese#增加属性Chinese.color='yellow'#删除属性del Chinese.color</function>

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>, 'talk': <function>, # 'eat': <function>, '__# dict__': <attribute>,#  '__weakref__': <attribute>, '__doc__': None}print(p1.__dict__)#{'name': 'zhang', 'age': 18}</attribute></attribute></function></function></function>

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>print(p1.talk)     #<bound>>print(p2.talk)     #<bound>></bound></bound></function>

可以看到,并不是,他们的内存地址都不一样。而且注意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
Python vs. C  : Understanding the Key DifferencesPython vs. C : Understanding the Key DifferencesApr 21, 2025 am 12:18 AM

Python and C each have their own advantages, and the choice should be based on project requirements. 1) Python is suitable for rapid development and data processing due to its concise syntax and dynamic typing. 2)C is suitable for high performance and system programming due to its static typing and manual memory management.

Python vs. C  : Which Language to Choose for Your Project?Python vs. C : Which Language to Choose for Your Project?Apr 21, 2025 am 12:17 AM

Choosing Python or C depends on project requirements: 1) If you need rapid development, data processing and prototype design, choose Python; 2) If you need high performance, low latency and close hardware control, choose C.

Reaching Your Python Goals: The Power of 2 Hours DailyReaching Your Python Goals: The Power of 2 Hours DailyApr 20, 2025 am 12:21 AM

By investing 2 hours of Python learning every day, you can effectively improve your programming skills. 1. Learn new knowledge: read documents or watch tutorials. 2. Practice: Write code and complete exercises. 3. Review: Consolidate the content you have learned. 4. Project practice: Apply what you have learned in actual projects. Such a structured learning plan can help you systematically master Python and achieve career goals.

Maximizing 2 Hours: Effective Python Learning StrategiesMaximizing 2 Hours: Effective Python Learning StrategiesApr 20, 2025 am 12:20 AM

Methods to learn Python efficiently within two hours include: 1. Review the basic knowledge and ensure that you are familiar with Python installation and basic syntax; 2. Understand the core concepts of Python, such as variables, lists, functions, etc.; 3. Master basic and advanced usage by using examples; 4. Learn common errors and debugging techniques; 5. Apply performance optimization and best practices, such as using list comprehensions and following the PEP8 style guide.

Choosing Between Python and C  : The Right Language for YouChoosing Between Python and C : The Right Language for YouApr 20, 2025 am 12:20 AM

Python is suitable for beginners and data science, and C is suitable for system programming and game development. 1. Python is simple and easy to use, suitable for data science and web development. 2.C provides high performance and control, suitable for game development and system programming. The choice should be based on project needs and personal interests.

Python vs. C  : A Comparative Analysis of Programming LanguagesPython vs. C : A Comparative Analysis of Programming LanguagesApr 20, 2025 am 12:14 AM

Python is more suitable for data science and rapid development, while C is more suitable for high performance and system programming. 1. Python syntax is concise and easy to learn, suitable for data processing and scientific computing. 2.C has complex syntax but excellent performance and is often used in game development and system programming.

2 Hours a Day: The Potential of Python Learning2 Hours a Day: The Potential of Python LearningApr 20, 2025 am 12:14 AM

It is feasible to invest two hours a day to learn Python. 1. Learn new knowledge: Learn new concepts in one hour, such as lists and dictionaries. 2. Practice and exercises: Use one hour to perform programming exercises, such as writing small programs. Through reasonable planning and perseverance, you can master the core concepts of Python in a short time.

Python vs. C  : Learning Curves and Ease of UsePython vs. C : Learning Curves and Ease of UseApr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software