How to do object-oriented programming in Python
Although Python is an interpreted language, it is object-oriented and can perform object programming. Let’s learn how to do object programming in Python.
1. How to define a class
Before doing object-oriented programming in Python, let’s first understand a few terms: class, class object, Instance objects, properties, functions and methods.
1. What is object-oriented
Object-oriented (oop) is an abstract method to understand the world, and everything in the world can Abstracted into an object, 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 How to do object-oriented programming in Python. 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

AI Hentai Generator
Generate AI Hentai for free.

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

How to download DeepSeek Xiaomi? Search for "DeepSeek" in the Xiaomi App Store. If it is not found, continue to step 2. Identify your needs (search files, data analysis), and find the corresponding tools (such as file managers, data analysis software) that include DeepSeek functions.

The key to using DeepSeek effectively is to ask questions clearly: express the questions directly and specifically. Provide specific details and background information. For complex inquiries, multiple angles and refute opinions are included. Focus on specific aspects, such as performance bottlenecks in code. Keep a critical thinking about the answers you get and make judgments based on your expertise.

Just use the search function that comes with DeepSeek. Its powerful semantic analysis algorithm can accurately understand the search intention and provide relevant information. However, for searches that are unpopular, latest information or problems that need to be considered, it is necessary to adjust keywords or use more specific descriptions, combine them with other real-time information sources, and understand that DeepSeek is just a tool that requires active, clear and refined search strategies.

DeepSeek is not a programming language, but a deep search concept. Implementing DeepSeek requires selection based on existing languages. For different application scenarios, it is necessary to choose the appropriate language and algorithms, and combine machine learning technology. Code quality, maintainability, and testing are crucial. Only by choosing the right programming language, algorithms and tools according to your needs and writing high-quality code can DeepSeek be successfully implemented.

Question: Is DeepSeek available for accounting? Answer: No, it is a data mining and analysis tool that can be used to analyze financial data, but it does not have the accounting record and report generation functions of accounting software. Using DeepSeek to analyze financial data requires writing code to process data with knowledge of data structures, algorithms, and DeepSeek APIs to consider potential problems (e.g. programming knowledge, learning curves, data quality)

Python is an ideal programming introduction language for beginners through its ease of learning and powerful features. Its basics include: Variables: used to store data (numbers, strings, lists, etc.). Data type: Defines the type of data in the variable (integer, floating point, etc.). Operators: used for mathematical operations and comparisons. Control flow: Control the flow of code execution (conditional statements, loops).

Java Made Simple: A Beginner's Guide to Programming Power Introduction Java is a powerful programming language used in everything from mobile applications to enterprise-level systems. For beginners, Java's syntax is simple and easy to understand, making it an ideal choice for learning programming. Basic Syntax Java uses a class-based object-oriented programming paradigm. Classes are templates that organize related data and behavior together. Here is a simple Java class example: publicclassPerson{privateStringname;privateintage;

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.
