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