Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the Python object?

2025-04-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "what is the Python object". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "what is the Python object".

The concept of classes and objects

Class is an abstraction of the objective things we have to deal with. Class is used to describe a collection of objects with the same properties and methods, which define the properties and methods common to each object in the collection. An object is an instance of a class in memory, and a class can be instantiated into multiple objects. Classes are abstract and do not take up memory, while objects are concrete and take up storage space.

Members of the class

As a beginner in Python, you don't have to spend your energy on puzzling concepts, you just need to master the basic elements of using classes. In the days to come, you will have enough time to experience the breadth and depth of OOP. With the accumulation of experience, OOP will naturally become your thinking tool.

The following code defines a class named A. All classes have constructors and destructors. In addition, they can contain member functions and member variables. I like to call member functions the methods of the class and member variables the properties of the class.

When a class is instantiated as an object, the constructor is executed first, and when the object is destroyed, the destructor is executed automatically. Typically, we do initialization in the constructor and clean up in the destructor.

At this point, many beginners must say: when I defined classes, I wrote constructors, but I never wrote destructors. Why do you say that all classes have constructors and destructors? Yes, when defining a class, these two methods exist even if we don't write constructors and destructors (the destructor is a little special, and we can't see it directly-- unless we define it ourselves). If we define the constructor and destructor ourselves, we will replace the two functions automatically assigned by the system. The following example clearly illustrates the mystery: class A has neither constructors nor destructors, class B has only destructors, both classes can generate class instances, or both can be destroyed, and the custom destructor is called first when del b.

New class and old class

In PY2, there are two kinds of classes: new class and old class. The new class needs to inherit from the virtual class Object, while the old class does not. There are three ways to write classes in PY2:

In PY3, there are only new classes, and old classes are no longer supported. If you are used to inheriting Object, there will be no problem at all. The above three writings are interpreted as new classes in PY3. The main differences between new and old classes are:

The new class can inherit the constructor and destructor of Object, which can be omitted if there is no special work on the constructor and destructor of the class. Old-fashioned classes cannot:

If you run with PY2 at this point, there will be an error: AttributeError: class A has no attribute'_ _ init__', will not get this error using PY3. If you change it to a new type of writing:

If you still run with PY2, you won't make an error.

New classes can use super:

In the case of multiple inheritance, the initialization and function search order of each parent class is different: the old class is depth-first inheritance and the new class is breadth-first inheritance.

Static and instance variables

The variables defined in the constructor are called instance variables. Instance variables can only be accessed in the way they are instantiated. Static variables are generally defined at the beginning of the class, independent of the constructor. Static variables can be accessed either in a way or in a way. Generally, the static variable of a class is used to hold the static property of the class, which can be used by the method of the class, but should not be modified by the method of the class.

Static function

Unlike other static functions of voice, there are two static functions of Python, both of which are implemented with decorators:

The Staticmethod function cannot use the Self parameter, so it cannot access any member variables, only the static variables of the class through the class name.

The Classmethod function also cannot use the Self parameter, so it cannot access any member variables, but it has a cls parameter. The cls parameter is not a reference to the object, but a reference to the class, and the static variable of the class can be accessed through the cls parameter.

Object-oriented three elements

Object-oriented, there are three elements: inheritance, encapsulation, and polymorphism. There are many concepts in it, and the more you talk about it, the more confused you become. In order not to mislead readers, I will try not to explain as much as possible. I will only give examples. Please figure it out for yourself.

(1) inheritance

If a derived class has only one parent class, it is single inheritance. This is the most common form of class definition.

If a derived class has more than one parent class, it is multiple inheritance.

Whether it's single inheritance or multiple inheritance, you can override the function of the parent class in a derived class-- this is called overriding.

(2) encapsulation

The so-called encapsulation is to integrate the member variables and member functions of the class, and protect or hide the key information. There are three levels of information protection or hiding: public, protection, and private. If you have any experience with C++, let's first review C++ 's information hiding rules:

Public members: visible to any code outside the class

Protected members: not visible to any code outside the class, but visible to derived classes

Private members: not visible to both external and derived classes.

Corresponding to these three levels, Python is defined as follows:

Members beginning with the English alphabet are public members

Members that begin with an underscore are protected members

Members of two underscore switches are private members

Let's try to see if Python's information protection or hiding rules are valid.

Try visiting public members:

The access rules for public members are the same as C++. Skip the protected members and look at the private members:

The access rules for private members are also the same as C++. Then why did I skip protecting the members? Let's try it:

It is not right to see here, only the code within the class and derived classes can be used, how can you use it directly? Yes, the access rules for Python's protected members are really different from those of C++. What kind of mechanism is the protective member of Python? It turns out that in the OOP of Python, there is no difference in protecting members, public members. Protection rules apply only in the case of from xxx import *.

TestA.py

Class A (object): passclass _ B (object): pass

TestB.py

From testA import * a = A () b = _ B ()

When performing testB.py:

Traceback (most recent call last): File "testB.py", line 4, inb = _ B () NameError: name'_ B' is not defined

At this point, the protected member _ B is protected. But this situation only applies to the case of from xxx import *. If testB.py writes like this:

TestB.py

From testA import A, _ Ba = A () b = _ B ()

Or:

Import testAa = testA.A () b = testA._B ()

There is no problem at all.

(3) Polymorphism

When the parent class has multiple derived classes, and the derived classes all implement the same member function, you can implement polymorphism:

Class H2O (object): def what (self): print ("I am H2O") class Water (H2O): def what (self): print ("I am water") class Ice (H2O): def what (self): print ("I am ice") class WaterVapor (H2O): def what (self): print ("I am water vapor"); def what (obj): obj.what () objs = [H2O (), Water (), Ice (), WaterVapor ()] for obj in objs: what (obj)

Abstract class

An abstract class cannot be instantiated, it can only be inherited by other classes as a parent class, and the derived class must implement all member functions in the abstract class. What is the application scenario of abstract classes? I've done a lot of script plug-ins to download data, and different data sources use different scripts, all of which require methods with the same name, so abstract classes come in handy.

Singleton mode

Singleton pattern (Singleton Pattern) is a commonly used software design pattern, the main purpose of which is to ensure that there is only one instance of a class. The singleton pattern comes in handy when you want only one instance of a class to appear in the entire system (such as a software configuration class, which is always that object no matter where the software is instantiated). For example, the log objects in the Python logging module, or the reactor in the asynchronous communication framework Twisted, are typical singleton patterns-although they are not necessarily implemented in the following approach.

Python can use singleton mode as a decorator:

> import abc > class A (object, metaclass=abc.ABCMeta): @ abc.abstractmethod def a (self): pass @ abc.abstractmethod def b (self): pass > class C (A): def a (self): print ("a") > > c = C () Traceback (most recent call last): File ", line 1, inc = C () TypeError: Can't instantiate abstract class C with abstract methods b Thank you for your reading. This is what Python objects are, after the study of this article. I believe that you have a deeper understanding of what the Python object is, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report