In Python, the definition of a class is implemented using the class keyword, with the following syntax:
class ClassName: '''类的帮助信息''' # 类文档字符串 statement # 类体
- ClassName : used to specify the class name, generally begins with an uppercase letter. If the class name includes two words, the first letter of the second word is also capitalized. This naming method is also called "hump-style nomenclature". This is the convention. . Of course, you can also name it according to your own habits, but it is generally recommended to name it by convention.
- Statement : A body consisting mainly of class variables (or class members), methods, and properties. If you don't think about the specific function of the class when defining the class, you can also use the pass statement instead of the class body.
- For example, let's declare a class with the geese as an example. The code is as follows:
class Animal: '''动物类''' pass
Create an instance of a class
The class statement itself does not create any instances of this class. So after the class definition is complete, you can create an instance of the class, that is, instantiate the object of the class. The syntax for creating an instance of a class is as follows:
Into the group: 548377875 to get dozens of sets of PDF!
- ClassName is a mandatory parameter used to specify a specific class;
- The parameterlist is an optional parameter. When a class is created, the __init__() method is not created, or the __init__() method has only one self parameter, the parameterlist can be omitted.
For example, to create an instance of the Geese class, you can use the following code:
wildGoose = Animal() # 创建动物类的实例 print(wildGoose) # 输出实例
After executing the above code, it will display something like the following:
<__main__.Animal object at0x0000000002F47AC8>
As you can see from the above execution results, wildGoose is an instance of the Geese class.
Method of creating a class
类中的方法与函数非常相似，可以理解为方法是在类中定义的函数。创建方法和创建函数类似，语法格式如下： def functionName(self,parameterlist): block
The parameters are as follows:
- functionName: used to specify the method name, usually starting with a lowercase letter;
- Self: a required parameter, representing an instance of a class whose name can be a word other than self. Using self is just a convention;
- Parameterlist: used to specify parameters other than the self parameter, each parameter is separated by a comma ",";
- Block: The method body, the specific functions implemented.
Description: The main difference between an instance method and a function in Python is that the function implements an independent function, and the instance method is a behavior in the implementation class, which is part of the class.
Once the instance method is created, it can be accessed through the instance name of the class and the dot (.) operator. The specific syntax is as follows:
- instanceName is the instance name of the class;
- functionName is the name of the method to be called;
- Parametervalue indicates that the corresponding actual parameter is specified for the method.
Create an Animal class and define three methods: eat(), play(), and sleep(). Instantiate the Animal class and call these 3 methods. Let's look at a sample code.
class Animal: # 创建动物类 '''动物类''' def eat(self): # 定义吃食物方法 print('正在吃食物') def play(self): # 定义玩耍方法 print('正在玩耍') def sleep(self): # 定义休息方法 print('正在休息') Dog = Animal() # 创建动物类的实例 Dog.eat() # 调用吃食物的方法 Dog.play() # 调用玩耍的方法 Dog.sleep() # 调用休息的方法
The result of the operation is as follows.
正在吃食物 正在玩耍 正在休息
Create the __init__() method
After the class is created, a __init__() method is usually created. This method is a special method, similar to the constructor in the Java language. Whenever you create a new instance of a class, Python will automatically execute it. The __init__() method must contain a self argument and must be the first argument. The self argument is a reference to the instance itself that is used to access the properties and methods in the class. The actual parameter self is automatically passed when the method is called. Therefore, when the __init__() method has only one argument, there is no need to specify the actual argument when creating an instance of the class.
Description: In the name of the __init__() method, there are two underscores at the beginning and end (no spaces in between). This is a convention designed to distinguish between Python default methods and normal methods. The following still declares a class with the geese as an example, and creates the __init__() method. Let's look at a sample code.
class Animal: # 创建动物类 '''大雁类''' def __init__(self): print('这是一个动物类') def eat(self): # 定义吃食物方法 print('正在吃食物') def play(self): # 定义玩耍方法 print('正在玩耍') def sleep(self): # 定义休息方法 print('正在大雁休息') Dog = Animal() # 创建动物类的实例 Dog.eat() # 调用吃食物的方法 Dog.play() # 调用玩耍的方法 Dog.sleep() # 调用休息的方法
The result of the operation is as follows.
这是一个动物类 正在吃食物 正在玩耍 正在大雁休息
As can be seen from the above results, when creating an instance of the geese, although the parameter is not specified for the __init__() method, the method is automatically executed.
In the __init__() method, in addition to the self parameter, you can customize some parameters, and the parameters are separated by a comma ",". For example, the following code will specify three more parameters when creating the __init__() method, namely name, gender, and weight.
class Animal: # 创建动物类 '''动物类''' def __init__(self,name,gender,weight): '''初始化赋值''' self.name = name self.gender = gender self.weight = weight def info(self): '''输出基本信息''' if self.gender == 'male': print('这只%s是公的' % self.name) else : print('这只%s是母的' % self.name) print('%s的重量是%s千克' % (self.name , self.weight)) dog = Animal('腊肠狗','male',10) # 创建动物类的实例 dog.info() # 调用实例的info方法，输出基本信息 cat = Animal('波斯猫','female',5) # 创建动物类的实例 cat.info() # 调用实例的info方法，输出基本信息
Execute the above code, the results are as follows:
这只腊肠狗是公的 腊肠狗的重量是10千克 这只波斯猫是母的 波斯猫的重量是5千克 上述代码中，__init__()方法的参数包含新创建的实例self和在调用类对象时提供的参数。在__init__()内，通过将属性分配给self来将其保存到实例中。例如，self.name = name表示将name属性保存在实例中。在新创建的实例返回到goods_a和goods_b后，使用点号（.）运算符即可访问这些属性以及类的属性。如goods_a.info()。点号（.）运算符属于属性绑定。访问属性时，首先会检查实例，如果不知道该属性的任何信息，则会对实例的类进行搜索。这是因为类和其所有实例共享其属性的底层机制。
Common mistakes: When creating the __init__() method for a class, run the following code in the development environment:
class Animal: '''动物类''' def __init__(): # 构造方法 print("这是动物类！") dog = Animal()# 创建动物类的实例
The exception information shown below will be displayed. The solution to this error is to add self in the parentheses of the third line of code.
Traceback (most recent call last): File "test.py", line 6, in <module> dog = Animal()# 创建动物类的实例 TypeError: __init__() takes 0 positional arguments but 1 was given
The role of self
When writing a class method, you must add a self to the beginning of the parameter list, but we have not assigned a value for this parameter, then what is the role of this self? In fact, self is a specific variable that refers to the object itself. By convention, it is given the name self. Of course, other names can be used, but the name self is strongly recommended because any programmer can recognize it at a glance.
So how does Python assign value to self? We still use animals as an example. Two instances of dog and cat are created in the Animal class. When calling this object's methods, such as dog.info(), Python will automatically convert it to Animal.info(dog). Similarly, when cat.info() is called, Python will automatically convert it to Animal.info(cat). If the info() function has parameters, for example:
def info(self,arg1,arg2): pass
Then when you call dog.info(arg1, arg2), Python will automatically convert it to Animal.info(dog, arg1, arg2).
Class attributes and instance attributes
The method in the class was introduced earlier. This section introduces another member of the class - the property. The so-called attribute can be understood as a variable defined in the class. According to the defined location, it can be divided into class attributes and instance attributes.
A class attribute is an attribute defined in a class and outside the function. Class attributes can share values between all instances of a class, that is, in all instantiated objects.
For example, define an Animal class and then define a class property with the following code:
class Animal: age = 5
Class properties can be called in two ways: class name, property name, and instance name. E.g:
class Animal: age = 5 print(Animal.age)# 类名调用属性，输出结果为 5 dog =Animal()# 实例化Animal类 print(dog.age)# 实例名调用属性,输出结果为 5 cat =Animal()# 实例化Animal类 print(cat.age)# 实例名调用属性,输出结果为 5
In the above code, the Animal class has an attribute age, so the value of Animal.age is 5. But why can two Animal instances of animal and cat get the age attribute? This is the function of attribute inheritance search. The following class tree diagram can explain this problem very well.
In the figure above, the Animal class has a property age, and two instances of dog and cat are created by the Animal class. When the dog.age is called, since the age attribute of the age instance does not exist, it will continue to search for Animal and find that there is an age attribute in the Animal class, so the dog.age is 5.
Note: If you call dog.name, since both the age instance and the Animal class do not have this property, the following error message is displayed: AttributeError: 'Animal' object has no attribute 'name'
Create an Animal class that has a property age and create two instances of dog and cat. If you change the initial value of the Animal class's property, will the dog.age and cat.age change? Let's take a look at an example.
class Animal: age = 5 dog = Animal() # 实例化Animal类 cat = Animal() # 实例化Animal类 dog.age = 10 Animal.age = 8 print('Animal类的age属性值为%s' % Animal.age) # 类名调用属性，输出结果为 8 print('dog实例的age属性值为%s' % dog.age) # 实例名调用属性,输出结果为 10 print('cat实例的age属性值为%s' % cat.age) # 实例名调用属性,输出结果为 8
The results are as follows.
Animal类的age属性值为8 dog实例的age属性值为10 cat实例的age属性值为8
In the above code, for the dog instance, dynamically add the attribute age, and dog.age looks for the age of the dog instance first, so the result is 10. Next, dynamically change the value of the age property of the Animal class, so the value of Animal.age becomes 8. Since the cat instance does not have an age attribute, the attribute of the Animal class is looked up. At this time, since the value of the age attribute of Animal has changed to 8, the cat.age is 8. The assignment process can be better understood by the following figure.
2. Instance properties
An instance attribute is an attribute defined in a method of a class and only acts on the current instance. The instance property is used when the __init__() method is created in Section 18.2.4.
Create an Animal class with 3 methods, __init__() initialization method, info() output detail method, and get_gender() method to determine the gender of the animal.
In the __init__() initialization method, set the instance property using self.name, self.gender, and self.weight.
class Animal: # 创建动物类 '''动物类''' def __init__(self,name,gender,weight): '''初始化赋值''' self.name = name self.gender = gender self.weight = weight def info(self): '''输出基本信息''' gender = self.get_gender(self.gender) print('这只%s是%s的' % (self.name,gender)) print('%s的重量是%s千克' % (self.name , self.weight)) def get_gender(self,gender): '''判断动物的性别''' if self.gender == 'male': gender = '公' else : gender = '母' return gender dog = Animal('腊肠狗','male',10) # 创建动物类的实例 dog.info() # 调用实例的info方法，输出基本信息 cat = Animal('波斯猫','female',5) # 创建动物类的实例 cat.info() # 调用实例的info方法，输出基本信息
The result of the operation is as follows.
这只腊肠狗是公的 腊肠狗的重量是10千克 这只波斯猫是母的 波斯猫的重量是5千克