Table of Contents
Constructor
Destructor
__str__method
__dict__
Home Backend Development Python Tutorial Introduction to common built-in members in Python object-oriented

Introduction to common built-in members in Python object-oriented

Apr 12, 2023 am 09:10 AM
python function develop

Okay, today we continue to analyze classes in Python.

[[441842]]

When we defined the class previously, we used the constructor. The constructor writing in Python is quite special. , it is a special function __init__. In fact, in the class, in addition to the constructor, there are many other functions in the format of __XXX__, and there are also some __xx__ attributes. Let’s talk about it one by one:

Constructor

Introduction to common built-in members in Python object-oriented

The constructor of all classes in Python is __init__, which is based on our needs , constructors are divided into parameterized constructors and parameterless constructors. If there is no constructor defined currently, the system will automatically generate an empty constructor with no parameters. For example:

Introduction to common built-in members in Python object-oriented

#In a class with an inheritance relationship, as long as the parent class is explicitly defined, the subclass will call the constructor of the parent class when it is created. Creating a parent class object will be executed automatically even if the subclass does not inherit properties from the parent class. For example:

Introduction to common built-in members in Python object-oriented

#If a subclass wants to inherit and obtain attributes from the parent class, it needs to explicitly call the constructor of the parent class to obtain them, otherwise it can only obtain the parent class methods. . For example:

Introduction to common built-in members in Python object-oriented

Here we need to introduce a new concept, namely function overloading. Within a class, if there are multiple functions with the same name and different function parameters (different numbers, types, and orders), then we call these functions overloaded functions, and the function return value is not used as the basis for overloading. We have similar concepts in java and C. However, Python is a dynamic programming language, and its data does not have data types. Therefore, we cannot overload functions inside the class. Therefore, there cannot be multiple methods with the same name inside the class, so our constructor method either does not write it, or we can only write one. . If you do not write it, the system will automatically generate an empty parameterless constructor; if you write it, you can only call this constructor. In addition, when we were learning about decorators, we seemed to have written several methods with the same name inside the class, for example:

Introduction to common built-in members in Python object-oriented

Then these methods with the same name are overloaded relationships Is it? No, because they are not complete methods. They must be complete with @property, @name.setter, and @name.deleter restrictions, so this is not a function overloading.

Destructor

The constructor is automatically executed when the object is created, and its main responsibility is to initialize the object. The destructor is automatically executed when the object is destroyed (del is executed or recycled), and its main responsibility is to recycle the object. If we did not write a destructor before, the system will automatically generate an empty destructor. Next we will write a destructor. The destructor method in Python is called __del__. For example:

Introduction to common built-in members in Python object-oriented

We call it like this:

Introduction to common built-in members in Python object-oriented

is executed as

Introduction to common built-in members in Python object-oriented

Here we want to focus on python’s garbage collection mechanism.

Currently programmers don’t pay special attention to the garbage collection mechanism of the system, because hardware is developing very fast now, and the resources available to us are very rich. Server memory of 4G is small, and most of them may start with 8G, which is not enough. add. But for some high-end jobs and high-precision industries, the garbage collection mechanism is still very important. So let’s sort out the garbage collection mechanism in python here.

The garbage collection mechanism in Python is mainly based on reference counting. The system assigns a reference counter to each object to record the number of times the current object is used. Since counting is involved, there are addition and subtraction operations. The system stipulates that the counter is incremented by 1 when the following conditions are met:

1. Create a new object

2. Reference an object

3. Pass the object as an actual parameter.

Decrease the counter by 1 when the following conditions are met:

1. Perform del operation on the object

2. The reference of the object is assigned a new value

3. The object exits the current scope (the most common is to exit the function scope)

In python, we pass sys. getrefcount (object name) to get the current reference counter of the object. Note that the reference count here is not necessarily 1 for the first time because there are temporary references by the system. Only when the reference counter pointing to the object becomes 0 (the initial value for the first time) will the object be actually destroyed and the object's destructor will be executed. For example:

Introduction to common built-in members in Python object-oriented

The output is

Introduction to common built-in members in Python object-oriented

Note that the above first call to sys.getrefcount(ad ) when the return value is 4, it means that the current system has other temporary uses, then we will return to the initial state as long as it reaches 4. When delad finally occurs, the temporary system references will also be released. Our current operating environment is win pycharm. Let’s change the code again:

Introduction to common built-in members in Python object-oriented

The output is

Introduction to common built-in members in Python object-oriented

As can be seen from the above output , the system seems to have other operations on basic data types, causing its initial reference count to be larger than we expected. The reference data type data is exactly what we expected.

Only when the object is finally released (when the reference count is 0), the __del__ destructor method will be executed.

__str__method

Let’s look at our code first:

Introduction to common built-in members in Python object-oriented

The output is

Introduction to common built-in members in Python object-oriented

When we print the object, we get the memory address of the object. Can we print our reference data type like we print the basic data type? For example, the above class Student should print His instance variables.

The __str__ method we mentioned now is to complete this function. The __str__ method has a return value. This return value is the output value when we execute print, so we can use __str__ Format the output content within the method. For example:

Introduction to common built-in members in Python object-oriented

The output is

Introduction to common built-in members in Python object-oriented

As can be seen from the above output, we want When outputting formatted reference data type data, you must override the __str__ method in this class. In this method, you can set the output content of the current content. This __str__ method is a method of the object class, because all classes in Python are directly or indirectly derived from object, so every reference data type has a __str__ method. We only need to override this method to override the method of the parent class. Otherwise, the system will call the __str__ method in object by default.

__dict__

Some people may have said, how do I know what built-in members (properties and methods) my class has? For example, I don’t know about the __str_ above. Method, how do I call it? There is indeed an attribute in the python class that can print out all the built-in content of the class. That is __dict__. Note that this __dict__ is an attribute, not a method. Do not add () when calling.

Introduction to common built-in members in Python object-oriented

The output is

Introduction to common built-in members in Python object-oriented

Why does stu1.__dict__ have less output content, while Student.__dict__ has more output content? Because stu1 is an object. For objects, the most meaningful thing is attributes, because methods are shared by all objects. of. The data is unique to itself. When executing, you only need to carry the address of the current object to execute the method of the class (ie, self). Student is a class, and a class is composed of attributes and methods, so the output of Student.__dict__ is slightly more, including methods and attributes.

If you want to know what built-in members the parent class of this class has, just print the __dict__ attribute of the parent class. For example, let’s take a look at the built-in members of the parent class object of the Student class, as follows:

Introduction to common built-in members in Python object-oriented

The output of Ojbect.__dict__ is a little longer, print it yourself and take a look , there must be a description of __str__ in it.

Okay, today we have come into contact with the __init__ constructor, __del__ destructor, __str__ built-in function, __dict__ attribute, etc. Tomorrow we will continue to analyze other built-in members in object-oriented.

The above is the detailed content of Introduction to common built-in members in Python object-oriented. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

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

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

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.

How to run programs in terminal vscode How to run programs in terminal vscode Apr 15, 2025 pm 06:42 PM

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.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

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.

Is the vscode extension malicious? Is the vscode extension malicious? Apr 15, 2025 pm 07:57 PM

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.

Python: Automation, Scripting, and Task Management Python: Automation, Scripting, and Task Management Apr 16, 2025 am 12:14 AM

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.

What is vscode What is vscode for? What is vscode What is vscode for? Apr 15, 2025 pm 06:45 PM

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 vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Golang vs. Python: Concurrency and Multithreading Golang vs. Python: Concurrency and Multithreading Apr 17, 2025 am 12:20 AM

Golang is more suitable for high concurrency tasks, while Python has more advantages in flexibility. 1.Golang efficiently handles concurrency through goroutine and channel. 2. Python relies on threading and asyncio, which is affected by GIL, but provides multiple concurrency methods. The choice should be based on specific needs.

See all articles