Home > Article > Backend Development > How to use Python classes and objects
We have actually come into contact with the concept of encapsulation before. Throwing messy data into the list is a kind of encapsulation, which is data level encapsulation; Packing commonly used code segments into a function is also a kind of encapsulation, is statement-level encapsulation; the object we want to learn now is also an idea of encapsulation. The source of the object is to simulate the real world. Encapsulates both data and code together.
For example, a turtle is an object in the real world, and it is usually described from two parts.
(1) Description from static characteristics: For example, green, with four legs, with a shell, etc. This is a static description. (2) Description from
dynamic behavior: For example, it will crawl, if you chase it, it will run, sometimes it will bite, sleep, etc., this is all from the behavioral aspect describe.
The characteristics of an object are called "properties", and The behavior of an object is called "methods". :
If the turtle is written as code, it will be as follows:
class Turtle: # Python中的类名约定以大写字母开头 # 特征的描述称为属性,在代码层面看来其实就是变量 color = 'green' legs = 4 shell = True # 方法实际就是函数,通过调用这些函数来完成某些工作 def climb(self): print('向前爬') def run(self): print('向前跑') def bite(self): print('咬人') def sleep(self): print('睡觉')The above code defines the characteristics (properties) and behavior (methods) of the
object , but it is not a complete object yet. The defined objects are called classes (Class) . You need to use a class to create a real object. This object is called an instance (Instance) of this class, also called Instance Objects (Instance Objects) . For example, this is like a factory that needs to produce a series of toys. It needs to first make a mold for the toy, and then mass-produce it based on the mold.
Create an object, also called instantiation of a class , is actually very simple:
# 首先要有上面那一段类的定义 tt = Turtle()
If you want toNote: The class name is followed by a small Parentheses, this is the same as calling a function. Therefore, in Python, class names start with uppercase letters, and functions start with lowercase letters , which makes them easier to distinguish. In addition, The assignment operation is not necessary, but if the created instance object is not assigned to a variable, the object cannot be used because there is no reference to the instance and it will eventually be garbage collected by Python The mechanism automatically recycles.
call the method in the object, use the dot operator (.) .
Class, Class ObjectAndInstance objectThree concepts:
As can be seen from this example,After assigning a value to the count attribute of the instance object c is equivalent to covering the count attribute of class object C. As shown in the figure below, if there is no assignment coverage, then the count attribute of the class object is referenced.
It should be noted that the attributes defined in the class arestatic variables. The attributes of the class are bound to the class object and will not depend on it. any instance object of it.
In addition,If the name of the attribute is the same as the method name, the attribute will override the method :
In order to avoid name conflicts, Some conventional rules should be followed: (1) Do not try to define all imaginable features and methods in a class. You should use inheritance and combination mechanisms for expansion.
(2) Use different parts of speech to name, such as nouns for attribute names, verbs for method names, and use camel case naming.
Python's self is actually equivalent to C's this pointer.
If you have not been exposed to any programming language before, then simply put, ifclasses are compared to drawings, then objects instantiated by classes are the real houses that can be lived in . Thousands of houses can be designed based on one drawing. They all look similar, but each house has a different owner. Everyone wants to find their own house, then self is equivalent to the house number here. With self, you can easily find your own house.
Python's self parameter is the same reason. Countless objects can be generated from a class. When an object method is called, the object will pass its own reference to the method as the first parameter, then Python will know which object method needs to be operated.
Give a simple example:
一般面向对象的编程语言都会区分公有和私有的数据类型,像C++和Java它们使用public和private关键字用于声明数据是公有的还是私有的,但在Python中并没有类似的关键字来修饰。
默认上对象的属性和方法都是公开的,可以直接通过点操作符(.)进行访问:
为了实现类似私有变量的特征,Python内部采用了一种叫name mangling(名字改编)的技术,在Python中定义私有变量只需要在变量名或函数名前加上“_ _”两个下划线,那么这个函数或变量就会成为私有的了:
这样,在外部将变量名“隐藏”起来了,理论上如果要访问,就要从内部进行:
但是认真想一下这个技术的名字name mangling(名字改编),那就不难发现其实Python只是把双下横线开头的变量进行了改名而已。实际上,在外部使用“_类名_ _变量名”即可访问双下横线开头的私有变量了:
说明:Python目前的私有机制其实是伪私有的,Python的类是没有权限控制的,所有的变量都是可以被外部调用的。
举个例子来说明继承。例如现在有个游戏,需要对鱼类进行细分,有金鱼(Goldfish)、鲤鱼(Carp)、三文鱼(Salmon)以及鲨鱼(Shark)。那么我们能不能不要每次都从头到尾去重新定义一个新的鱼类呢?因为我们知道大多数鱼的属性和方法是相似的,如果有一种机制可以让这些相似的东西得以自动传递,那么就方便多了。这就是继承。
继承的语法很简单:
c l a s s 类 名 ( 被 继 承 的 类 ) : . . . class 类名(被继承的类): \\ \quad ... class类名(被继承的类):...
被继承的类称为基类、父类或超类;继承者称为子类,一个子类可以继承它的父类的任何属性和方法。
举个例子:
需要注意的是,如果子类中定义与父类同名的方法或属性,则会自动覆盖父类对应的方法或属性:
接下来,尝试写一下开头提到的金鱼(Goldfish)、鲤鱼(Carp)、三文鱼(Salmon)以及鲨鱼(Shark)的例子。
import random as r class Fish: def __init__(self): self.x = r.randint(0, 10) self.y = r.randint(0, 10) def move(self): # 这里主要演示类的继承机制,就不考虑检查场景边界和移动方向问题 # 假设所有的鱼都是一路向西游 self.x -= 1 print("我的位置是:", self.x, self.y) # 金鱼 class Goldfish(Fish): pass # 鲤鱼 class Carp(Fish): pass #三文鱼 class Salmon(Fish): pass # 上面三种鱼都是食物,直接继承Fish类的全部属性和方法 # 下面定义鲨鱼类,除了继承Fish类的属性和方法,还要添加一个吃的方法 class Shark(Fish): def __init__(self): self.hungry = True def eat(self): if self.hungry: print("吃掉你!") self.hungry = False else: print("太饱了,吃不下了~")
首先运行这段代码,然后进行测试:
同样是继承于Fish类,为什么金鱼(goldfish)可以移动,而鲨鱼(shark)一移动就报错呢?
可以看到报错提示为:Shark对象没有x属性,这是因为在Shark类中,重写了_ _init_ _()方法,但新的_ _init_ _()方法里面没有初始化鲨鱼的x坐标和y坐标,因此调用move()方法就会出错。
那么解决这个问题,只要在鲨鱼类中重写_ _init_ _()方法的时候先调用基类Fish的_ _init_ _()方法。
下面介绍两种可以实现的技术:
(1)调用未绑定的父类方法
(2)使用super函数
什么是调用未绑定的父类方法?举个例子:
修改之后,再运行下发现鲨鱼也可以成功移动了:
这里需要注意的是,这个self并不是父类Fish的实例对象,而是子类Shark的实例对象。所以这里说的未绑定是指并不需要绑定父类的实例对象,使用子类的实例对象代替即可。
The super function can help us automatically find the method of the base class, and also pass in the self parameter for us, so there is no need Do these things:
Get the same result after running:
In addition, Python also supports multiple inheritance, which means you can inherit the properties and methods of multiple parent classes at the same time:
c l a s s class name (parent class 1, parent class 2, parent class 3, . . .): . . . class class name (parent class 1, parent class 2, parent class 3,...):\\ \quad ... class class name (parent class 1, parent class 2, parent class 3,...):...
For example:
This is the basic multiple inheritance syntax, but multiple inheritance can easily lead to code confusion, so when you are not sure whether you really have to use multiple inheritance, please try to avoid using it, because Sometimes unforeseen bugs may occur.
We have learned the concept of inheritance before, and mentioned multiple inheritance, but if we now have turtles and fish, we are now required to define a class called a pool, and the pool must There are turtles and fish. It seems strange to use multiple inheritance, because the pool, the turtle, and the fish are different species, so how to combine them into a pool class?
In fact, it is very simple in Python. Just put the required class into it and instantiate it. This is called combination:
Run the above code first, and then test:
Python objects have many magics method, if your object implements one of these methods, then this method will be called by Python under special circumstances, and all of this happens automatically.
The _ _init_ _() method is usually called the construction method. As long as an object is instantiated, This method Will be automatically called when the object is created. Parameters can be passed in when instantiating an object. These parameters will be automatically passed into the _ _init_ _() method. You can customize the initialization operation of the object by overriding this method.
For example:
Some readers may ask, sometimes the _ _init_ _() method is written in the class definition , sometimes not, why? Look at the following example:
It should be noted here that the return value of the _ _init_ _() method must be None and cannot be other :
So, generally rewrite the _ _init_ _() method when initialization is required. So this _ _init_ _() method is not the first method called when instantiating an object.
_ _new_ _(cls[, …]) method_ _new_ _() method isThe first method called when an object is instantiated. Different from other methods, its first parameter is not self but the class (cls) , and other parameters will be passed directly to the _ _init_ _() method.
_ _new_ _() method requiresto return an instance object, usually the object instantiated by the cls class. Of course, you can also return other objects.
_ _new_ _() method rarely rewrites it. Generally, Python can be executed with the default scheme. Butthere is a situation where you need to override this method , that is When inheriting an immutable type , its characteristics become particularly important.
_ _del_ _(self) destructor methodIf the _ _init_ _() and _ _new_ _() methods are the constructors of objects , then Python also provides a destructor called the _ _del_ _() method.When the object is about to be destroyed, this method will be called. However, it should be noted that del x is not equivalent to automatically calling x._ _del_ _(). The _ _del_ _() method is called when the garbage collection mechanism recycles this object. for example:
The concept of binding was mentioned earlier, but what is binding? Python strictly requires that methods need to have an instance before they can be called. This restriction is actually the so-called binding concept of Python.
Someone may try this and find that they can also call:
However, there is a problem with this, that isAccording to the object instantiated by the class, the functions inside cannot be called at all:
In fact, due to the binding mechanism of Python, the bb object is automatically used as The first parameter is passed in, so TypeError occurs.
Look at another example:
_ _dict_ _The attribute is composed of a dictionary, and there are only instances in the dictionary The object's attributes do not display class attributes and special attributes. The key represents the attribute name , and the value represents the corresponding data value of the attribute.
Now the instance object dd has two new attributes, and these two attributes only belong to the instance object:
Why is this? In fact, this is entirely due to the self parameter: when the instance object dd calls the setXY method, the first parameter it passes in is dd, so self.x = 4, self.y = 5 Equivalent to dd.x = 4, dd.y = 5, so x and y cannot be seen in the instance object or even the class object, because these two attributes only belong to the instance object dd .
If the class instance is deleted, can the instance object dd still call the printXY method? The answer is yes:
The above is the detailed content of How to use Python classes and objects. For more information, please follow other related articles on the PHP Chinese website!