


Introduction to common built-in members in Python object-oriented
Okay, today we continue to analyze classes in Python.
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

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:

#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:

#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:

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:

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:

We call it like this:

is executed as

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:

The output is

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:

The output is

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:

The output is

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:

The output is

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.

The output is

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:

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!

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.

Python and C have significant differences in memory management and control. 1. Python uses automatic memory management, based on reference counting and garbage collection, simplifying the work of programmers. 2.C requires manual management of memory, providing more control but increasing complexity and error risk. Which language to choose should be based on project requirements and team technology stack.

Python's applications in scientific computing include data analysis, machine learning, numerical simulation and visualization. 1.Numpy provides efficient multi-dimensional arrays and mathematical functions. 2. SciPy extends Numpy functionality and provides optimization and linear algebra tools. 3. Pandas is used for data processing and analysis. 4.Matplotlib is used to generate various graphs and visual results.

Whether to choose Python or C depends on project requirements: 1) Python is suitable for rapid development, data science, and scripting because of its concise syntax and rich libraries; 2) C is suitable for scenarios that require high performance and underlying control, such as system programming and game development, because of its compilation and manual memory management.

Python is widely used in data science and machine learning, mainly relying on its simplicity and a powerful library ecosystem. 1) Pandas is used for data processing and analysis, 2) Numpy provides efficient numerical calculations, and 3) Scikit-learn is used for machine learning model construction and optimization, these libraries make Python an ideal tool for data science and machine learning.

Is it enough to learn Python for two hours a day? It depends on your goals and learning methods. 1) Develop a clear learning plan, 2) Select appropriate learning resources and methods, 3) Practice and review and consolidate hands-on practice and review and consolidate, and you can gradually master the basic knowledge and advanced functions of Python during this period.

Key applications of Python in web development include the use of Django and Flask frameworks, API development, data analysis and visualization, machine learning and AI, and performance optimization. 1. Django and Flask framework: Django is suitable for rapid development of complex applications, and Flask is suitable for small or highly customized projects. 2. API development: Use Flask or DjangoRESTFramework to build RESTfulAPI. 3. Data analysis and visualization: Use Python to process data and display it through the web interface. 4. Machine Learning and AI: Python is used to build intelligent web applications. 5. Performance optimization: optimized through asynchronous programming, caching and code

Python is better than C in development efficiency, but C is higher in execution performance. 1. Python's concise syntax and rich libraries improve development efficiency. 2.C's compilation-type characteristics and hardware control improve execution performance. When making a choice, you need to weigh the development speed and execution efficiency based on project needs.


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 Mac version
God-level code editing software (SublimeText3)

Dreamweaver Mac version
Visual web development tools

WebStorm Mac version
Useful JavaScript development tools

Zend Studio 13.0.1
Powerful PHP integrated development environment