How to write classes in python

Class definition

In Python, the definition of a class is through the class keyword. For example, we define a class that stores student information:

classStudent(object):
pass

The class name is immediately followed by the class name, that is, Student. The class name is usually a capitalized word, followed by (object), indicating which class the class is inherited from. Usually, if there is no suitable inheritance class, the object class is used, which is the class that all classes will eventually inherit.

After the Student class is defined, an instance of Student can be created based on the Student class. The creation of the instance is achieved by the class name + ():

 bart =Student()
 bart
<__ main__.Student object at 0x10a67a590 
 Student
< class'__main__.Student'

As you can see, the variable bart points to an instance of Student, the following 0x10a67a590 is the memory address, the address of each object is different, and the Student itself is a class.

You can freely bind attributes to an instance variable, for example, bind a name attribute to the instance bar:

 bart.name ='Bart Simpson'
 bart.name
' Bart Simpson'

This is different from static languages such as C++. We can add attributes to an object at any time.

In python, the attributes of the class are equivalent to the member variables of the C++ class, and the methods of the class are equivalent to the member functions of the C++ class.

Since the class can act as a template, when creating an instance, some properties that we think must be bound can be mandatory to fill in. By defining a special init method, when an instance is created, attributes such as name and score are bound to it:

classStudent(object):
 def __init__(self, name, score):
 self.name = name
 self.score = score

Compared with C++, the init function is equivalent to the constructor of the C++ class. Note: There are two underscores before and after the special method "init".

Note that the first parameter of the init method is always self, which represents the created instance itself. Therefore, within the init method, various properties can be bound to self, because self points to the created instance itself.

With the init method, when creating an instance, you cannot pass in empty parameters. You must pass in parameters that match the init method, but self does not need to be passed. The Python interpreter itself will pass in the instance variables:

 bart =Student('Bart Simpson',59)
 bart.name
' Bart Simpson'
 bart.score
59

Compared with ordinary functions, the functions defined in the class have only one difference, that is, the first parameter is always the instance variable self, and there is no need to pass this parameter when calling. In addition, the methods of the class are no different from ordinary functions, so you can still use default parameters, variable parameters, keyword parameters, and named keyword parameters.

We can add new methods to the Student class we defined, such as get_grade:

classStudent(object):...

 def get_grade(self):if self.score  =90:return'A'
 elif self.score  =60:return'B'else:return'C'

Knowledge point expansion:

Build and initialize

I believe everyone is familiar with this most basic magic method init. It allows you to customize the initialization behavior of an object. And when I call x=SomeClass(), init is not the first to be called. In fact, there is a method called new. In fact, it creates an instance, and it passes any parameters to the initializer to achieve the purpose of creation. At the end of the object's life cycle, __ del__ is called. Let's take a closer look at these 3 magic methods:

__ new__(cls,[…)

When an object is instantiated, new is the first method called. Pass any other parameters to init in the class. new is rarely used, and it does have its purpose, especially when a subclass inherits an immutable type (a tuple or a string). I don't plan to pursue the details of __ new __ anymore, because it won't be of much use, because a very detailed explanation is already covered in the Python Docs.

__ init__(self,[…)

Initialization of the class. It will get anything passed by the initial build call (for example, when we call x=SomeClass(10,'foo'), init will pass the passed 10 and'foo' as parameters. init It is almost universally used in Python class definitions)

__ del__(self)

If new and init are the constructors of the object, then del is the destructor. It does not implement the behavior declared as del x (such code will not be interpreted as x.__ del__()). Instead, it is defined as the behavior when an object is garbage collected. This may be useful for objects that may require additional cleanup, such as sockets or file objects. But be careful, if the object is still alive and when the interpretation exits, __ del__ is not guaranteed to be executed, so such __ del__ cannot be used as a substitute for good coding practices. (Just like when you are done, you always have to close a connection. But in fact, __ del__ is almost never executed because it is called in an unsafe situation. Be vigilant when using it!)

This is the end of this article on how to write classes in python. For more related methods of writing classes in python, please search ZaLou.Cn

Recommended Posts

How to write classes in python
How to write return in python
How to write win programs in python
How to write try statement in python
Teach you how to write games in python
How to write a confession program in python
How to write python configuration file
How to wrap in python code
How to omit parentheses in Python
How to filter numbers in python
How to read Excel in Python
How to view errors in python
How to understand variables in Python
How to clear variables in python
How to use SQLite in Python
How to delete cache files in python
How to introduce third-party modules in Python
How to represent null values in python
How to save text files in python
How to run id function in python
How to install third-party modules in Python
How to custom catch errors in python
How to define private attributes in Python
How to add custom modules in Python
How to understand global variables in Python
How to view installed modules in python
How to open python in different systems
How to sort a dictionary in python
How to add background music in python
How to represent relative path in python
Write gui in python
How to use the round function in python
How to use the zip function in Python
How to program based on interfaces in Python
How to install python in ubuntu server environment
How to simulate gravity in a Python game
How to use the format function in python
How to use code running assistant in python
How to set code auto prompt in python
How to delete files and directories in python
How to install the downloaded module in python
How to read and write files with Python
How to perform continuous multiplication calculation in python
How to write Pythonic code
How to learn python quickly
How to uninstall python plugin
How to understand python objects
How to use python tuples
How to understand the introduction of packages in Python
How to understand a list of numbers in python
Example of how to automatically download pictures in python
How to save IE as an attachment in python
How to create a Python virtual environment in Ubuntu 14.04
How to install Helm in Ubuntu
How to use hanlp in ubuntu
How to use python thread pool
How to find the area of a circle in python
How to save the python program
How to install mysql in Ubuntu 14.04
How to install Python 3.8 on CentOS 8
How to install Python 3.8 on Ubuntu 18.04