Object-oriented two (class creation and call + class attributes and methods + special parameters Self + initialization method init) 2020-11-24

1. Class

When we say that they belong to the same category, there is a consensus hidden that things of the same category have common characteristics. For example, we are all Chinese, and Chinese are a class of people with some things in common: black eyes, black hair, yellow skin, use chopsticks, and speak Chinese. And these common points are the basis for distinguishing me from other types. These characteristics can be divided into two types if subdivided:

  • The first is to describe how things are like, such as black hair, dark eyes, yellow skin
  • The second is to describe what things can do, what actions and functions they have. Such as eating with chopsticks, can speak Chinese.
    In the programming world, we call the first feature attributes , and the second feature called methods .
    Each class in Python has its own attributes and methods, and each instance object can call these attributes and methods.

1.1 Class creation

We first create a computer class:

class Computer:
	screen=True
	def start(self):
		print('电脑正在开机中')

Computers have screens, and the property screen is True.
It will display when booting: The computer is booting.
Let's take a concrete look at the syntax of creating a class:
Insert picture description here
the creation statement of an instance method is very similar to the definition statement of a function. The only difference is that there is a parameter self that must be placed in the first place in the instance method.
The first letter of the class name should be capitalized so that we can easily recognize "Oh! This is a class!"
Example: Create a Chinese human, and create an attribute and method.

class Chinese:
	eye=dark
	def speak(self):
		print('母语讲中文')

So we created a simple class. But if I run the code, there will be no results and no errors will be reported. Because we created the class, but haven't called the class yet.

1.2 Class call

Below we call the class we just created:

class Chinese:
	eye=dark
	def speak(self):
		print('母语讲中文')
xiaoming=Chinese()
print(xiaoming.eye)
xiaoming.speak()

Results As a
Insert picture description here
result, an error occurred when I called directly, saying that dark was not defined. That's because dark didn't use quotation marks and treated them as variables.

class Chinese:
	eye='dark'
	def speak(self):
		print('母语讲中文')
xiaoming=Chinese()
print(xiaoming.eye)
xiaoming.speak()

Execution result
Insert picture description here
The key to the call is the 9th line of code: xiaoming = Chinese(). This process is called: class instantiation, that is, creating an instance object under a certain class. So far we have created an instance that can call all the properties and methods of the class. The syntax is as follows:

实例名=类名()
xiaoming=Chinese()

Let's try to print the instance type and print out the instance directly. What will be the result?

class Chinese:
	eye='dark'
	def speak(self):
		print('母语讲中文')
xiaoming=Chinese()
print(type(xiaoming)
print(xiaoming)

Insert picture description here

We see that Xiaoming belongs to the Chinese class. Xiaoming is an object of the Chinese class. The memory address of the object is: 0x000001A3D45694C0. Once
the instance my_computer is created, the properties and methods in the class can be called. In one sentence, there will be all instances of the class.

1.3 Calling properties and methods

Syntax:. Instance name and instance name attribute method.
Example:

class Chinese:
	eye='dark'
	def speak(self):
		print('母语讲中文')
xiaoming=Chinese()
print(xiaoming.eye)
xiaoming.speak()

Insert picture description here
When the instance calls the properties of the class, the order of the parser search is to search in the object of the instance first, and if it does not go to the object of the class to which it belongs, output the property if there is the property in the object of the instance, if there is no output The attribute value of the attribute name of the class object to which it belongs, and an error will be reported if there is not yet.
example:

class Chinese:
	eye='dark'
	def speak(self):
		print('母语讲中文')
xiaoming=Chinese()
xiaogang=Chinese()
xiaogang.eye='双眼皮'
xiaohong=Chinese()
print(xiaoming.eye,xiaogang.eye,xiaohong.eye)

Insert picture description here
If I call a property that neither the current instance object nor this class object has, an error will be reported, such as:

class Chinese:
	eye='dark'
	def speak(self):
		print('母语讲中文')
xiaohong=Chinese()
print(xiaohong.hair)

Insert picture description here
What if there are attributes to be called in the current instance and the class it belongs to? It will look up in the order we just mentioned by the parser, first looking up in the current instance object, and calling it if there is one, instead of looking up in the properties of the class object. If all, follow the principle of proximity.
Insert picture description here
They belong to black hair, but Xiao Hong's red hair is probably dyed, just kidding. If Xiao Hong's hair color is to be used, of course it is her own red hair. If you don't know what hair color she is, then the black hair in the category will be called.
Insert picture description here

Summary description:

  • Both class objects and instance objects can save properties and methods
  • If a property or method is shared by all instances, it should be stored in the class object
  • If a property or method is unique to an instance, it should be stored in the instance object
  • In general, the properties are stored in the instance object, because most of the properties are independently owned
  • In general, the method is saved to the class object
  • Summarizing the three steps is: create a class-instantiation of the class-use the instance to call the properties and methods of the class.

One more word: the properties and methods created in a class can be called by all its instances, and the number of instances is theoretically unlimited. As in the example above, I created three instances of xiaoming=Chinese, xiaohong=Chinese, and xiaogang=Chinese. Therefore, a class is like an "instance factory" because it provides a set of blueprints for all instances (that is, what properties and methods are preset).

2. Special parameters: self

When defining the method of a class earlier, everyone noticed that there was a parameter self in the parentheses. This parameter is necessary for definition, but must be ignored when calling. Why is this? Let's explain slowly below.

2.1 The role of the self parameter

The function of the special parameter self is officially revealed: self will receive the data passed in during the instantiation process. When the instance object is created, the instance will replace self and run in the code. In other words, self is a stand- in for all instances. What does "stand-in" mean? Let's look at an example. The class methods we just listed have only one self parameter. In fact, like general functions, class methods can also set multiple parameters:

class Chinese:
	name='Li Guanghui'
	def speak(self, someone):
		print(someone+'是中国人')
person1=Chinese()
print(person1.name)
person1.speak()

Insert picture description here

An error is reported, one parameter is missing in the speak() method. We pass in a person's name.

class Chinese:
	name='Li Guanghui'
	def speak(self, someone):
		print(someone+'是中国人,说汉语。')
person1=Chinese()
print(person1.name)
person1.speak('Li Guanghui')

Insert picture description here
Ignore when calling self.
Although it is correct to pass'Li Guanghui' to the parameter someone , it is actually unnecessary, because as long as the class attribute'Li Guanghui' is called inside the say method, the same function can be achieved without repeated passing. Participate.
How to call the class attribute inside the method? You might want to write:

class Chinese:
	name='Li Guanghui'
	def speak(self):
		print(name+'是中国人,会说汉语。')
person1=Chinese()
person1.speak()

But writing this way will report an error.
Insert picture description here
Person1 is an instance of the Chinese class and cannot access the variable name. Remember what we just said, if we want to call a class attribute outside of the class, we have to create an instance first, and then call it in the format of instance name and attribute? So if we want to call the class attribute inside the class, and before the instance is created, we need a variable to replace the instance to receive data, this variable is the parameter self.
The correct writing should be like this:

class Chinese:
	name='Li Guanghui'
	def speak(self):
		print(self.name+'是中国人,会说汉语。')
person1=Chinese()
person1.speak()

Insert picture description here

When the last line of code runs, the instance person1 will be passed to self as a parameter, replacing self. The self.name in line 67 is equivalent to person1.name. person1.name is equivalent to calling the class attribute name (ie'Li Guanghui'), and then running the entire method.
His role is relative (contrast with the code above):

class Chinese:
	name='Li Guanghui'
	def speak(person1):
		print(person1.name+'是中国人,会说汉语。')
person1=Chinese()
person1.speak()

And here is not that self is actually equivalent to itself, that is, the parameter of the instance object itself, no matter what instance is created later, self will be replaced by the instance name.
Insert picture description here
It can be seen that the role of self is equivalent to occupying a position for the instance first, and when the instance is created, it will "retire and resign to the virtuous".

2.2 Further understanding of the self parameter

Next, I want to deepen my understanding of the self parameter through an example.
Example: Define a class and implement different properties when different instances call class properties.

class Chinese:
	hair='黑色'
	def speak(self):
		print('我的头发颜色是黑色')
xiaoming=Chinese()
xiaohong=Chinese()
xiaoming.speak()
xiaohong.speak()

If the code is written as above, the output is like this: The
Insert picture description here
result is "My hair color is black", and what I want to achieve is that Xiaoming's hair is black and Xiaohong's hair is red.
I thought of using format string knowledge to handle it like this:

class Chinese:
	hair='黑色'
	def speak(self):
		print('我的头发颜色是%s'%hair)
xiaoming=Chinese()
xiaohong=Chinese()
xiaoming.speak()
xiaohong.speak()

Insert picture description here
The result was an error, saying that the variable hair is not defined. We remember that in the function, the function can read the externally defined variables, but the external cannot read the internally defined variables. But it is not possible in the class. It is not possible to directly call external variables in a class, and must be called with the syntax of instance name and attribute name . and so:

class Chinese:
	hair='黑色'
	def speak(self):
		print('我的头发颜色是%s'%xiaoming.hair)
xiaoming=Chinese()
xiaohong=Chinese()
xiaoming.speak()
xiaohong.speak()

Insert picture description here

No error was reported this time, but it was all black. So I thought of defining the properties of the instance itself:

class Chinese:
	hair='黑色'
	def speak(self):
		print('我的头发颜色是%s'%xiaoming.hair)
xiaoming=Chinese()
xiaoming.hair='黑色'
xiaohong=Chinese()
xiaohong.hair='红色'
xiaoming.speak()
xiaohong.speak()

Insert picture description here
But the problem reappeared. When I passed the parameters, I could only write the name of one person at a time, either xiaoming or xiaohong. Is there a way to change this parameter when the instance changes? At this time I pay attention to the self parameter, will it meet my expectations? I call with instances of different classes, and then print self.

class Chinese:
	hair='黑色'
	def speak(self):
		print(self)
		#print('我的头发颜色是%s'%xiaoming.hair)
xiaoming=Chinese()
#xiaoming.hair='黑色'
xiaohong=Chinese()
#xiaohong.hair='红色'
xiaoming.speak()
xiaohong.speak()

Insert picture description here
I was pleasantly surprised to find that when the speak() method is called with different instances, the memory address of self is different, which shows that it is two completely different objects. We further study the relationship between self and instance objects.

class Chinese:
	hair='黑色'
	def speak(self):
		print(self)
xiaoming=Chinese()
print(xiaoming)

Insert picture description here
We found that the memory address of the object xiaoming and the memory address of self are exactly the same, indicating that they are the same object. What about when xiaohong called?

class Chinese:
	hair='黑色'
	def speak(self):
		print(self)
xiaoming=Chinese()
xiaohong=Chinese()
print(xiaoming)
xiaoming.speak()
print(xiaohong)
xiaohong.speak()

Insert picture description here
We found that when the instance objects are different, the self object and the instance object remain the same.
Through research, we found that if xiaoming calls self, it means xiaoming, and if xiaohong calls self, it means xiaohong. Then, we can directly deal with the above problem like this:

class Chinese:
	hair='黑色'
	def speak(self):
		print('我的头发颜色是%s'%self.hair)
xiaoming=Chinese()
xiaoming.hair='黑色'
xiaohong=Chinese()
xiaohong.hair='红色'
xiaoming.speak()
xiaohong.speak()

Insert picture description here
This is what achieved our purpose. There should be flowers here.
In summary, so we say that self represents the instance of the class itself, which facilitates the flow of data. In this regard, we need to remember two points:

  • The first point: As long as you use def to create a method in a class, you must leave the first parameter position to self, and ignore it when calling the method (don’t pass parameters to self)
  • The second point: When you want to call class properties or other methods within a class method, you must use the format of self. property name or self. method name.

Well, the magic parameter self is explained here. For beginners, it is really not that easy to understand. If you are not familiar with it, you can review it a lot and consolidate it by doing exercises after class.

3. Initialization method (constructor)

The format of defining the initialization method is def init (self), which is composed of init plus the left and right underscores (the abbreviation of initialize "initialization").
The function of the initialization method is: when each instance object is created, the code in the method will run automatically without calling it.

3.1 The first introduction of the initialization method

example:

class Chinese:
	def __init__(self):
		print('很高兴遇见你,我是初始化方法')
person1=Chinese()

Insert picture description here
Isn’t it amazing? We just created the instance, and the initialization method is executed automatically before calling it!
Using this feature, in writing habits, we will complete the creation of the class attribute inside the initialization method, and set the initial value for the class attribute, so that other methods in the class can be called directly and at any time. Let's look at an example:

class Chinese:
	def __init__(self):
		self.mouth=1
		self.eye=2
	def speak(self):
		print('我有%s张嘴,%s只眼'% (self.mouth,self.eye))
person_01=Chinese()
person_01.speak()

Insert picture description here
Note the format of the attributes created in the reinitialization method:

self.mouth=1
self.eye=2

The self in the variable must not be lost.
In addition to setting fixed constants, the initialization method can also receive other parameters, so that the incoming data can be used as attributes to flow between the methods of the class. Let's look at another example:

class Chinese:
	def __init__(self,name,birth,region):
		self.name=name
		self.birth=birth
		self.region=region
	def speak(self):
		print('我是%s,出生于%s年,我的出生地是%s'%(self.name,self.birth,self.region))
guanghui=Chinese('Guanghui',1982,'Henan')
guanghui.speak()

Insert picture description here
Observe carefully: In the
162 lines of code, there are not only special parameters but also three other formal parameters when defining the initialization method.
In the 163-165 lines of code, define the initialization variables and assign the formal parameters to them, so that the actual parameters passed in directly become the values ​​of the initialization variables. Of course, it doesn't have to be self.name=name, it can also be self.abc=name. This is arbitrary, as long as the variable passed in later is consistent with the definition.
In the 168 lines of code, remember to pass in the required actual parameters when the class is instantiated, otherwise an error will be reported.
Insert picture description here
The error here says that three positional parameters are missing.
As the functions we want to implement become more and more complex, we will write a lot of methods inside the class. If the data we need to pass in can be stored in the class for a long time and can be called at any time, the initialization method is a good solution.
Exercise: Add the following code to achieve the following print result: Where were you born? I was born in Henan.

class Chinese:
    def 

    
    def born(self):
        print('我出生在%s。' % self.hometown)

guanghui = Chinese('河南')
guanghui.born()

answer:

class Chinese:
    def __init__(self,hometown):
    	self.hometown=hometown   
    def born(self):
        print('我出生在%s。' % self.hometown)

guanghui = Chinese('河南')
guanghui.born()

Insert picture description here

3.2 Another introduction of initialization method

example:

class Chinese:
	name='葫芦娃'
	def speak(self):
		print('大家好,我是%s'%self.name)
p_01=Chinese()
p_01.speak()

Insert picture description here
Now I want to create a few more instance objects, and different instance objects have different names.

class Chinese:
	# name='葫芦娃'
	def speak(self):
		print('大家好,我是%s'%self.name)
p_01=Chinese()
p_01.name='钢铁侠'
p_01.speak()
p_02=Chinese()
p_02.name='蜘蛛侠'
p_02.speak()
p_03=Chinese()
p_03.name='绿巨人'
p_03.speak()
p_04=Chinese()
p_04.name='黑寡妇'
p_04.speak()

Output result

大家好,我是钢铁侠
大家好,我是蜘蛛侠
大家好,我是绿巨人
大家好,我是黑寡妇

It is not only troublesome to define different attributes in this way, but if one forgets the definition, it will not be reminded, which will cause an error during execution.
To this end, we can use a special method to solve the problem.

class Chinese:
	def __init__(self,name):
		self.name=name  #这里的self.name不一定是这样写,可以写self.abc

	def speak(self):
		print('大家好,我是%s'%self.name)
p_01=Chinese('钢铁侠')
p_01.speak()
p_02=Chinese('蜘蛛侠')
p_02.speak()
p_03=Chinese('绿巨人')
p_03.speak()
p_04=Chinese('黑寡妇')
p_04.speak()

Insert picture description here
The advantage of this special method is that if you instantiate the class object, you must pass in the required actual parameters, and the non-passing will cause an error reminder. Moreover, you don’t need to add the properties of the instance one by one. It is directly passed in as a parameter, and it will be received by self.name in the initialization method as the attribute value. Once the instance is created, the initialization method runs immediately, which is equivalent to direct creation The properties of the instance object.

4. Homework

4.1 Blogging and sorting out knowledge points

4.2 Type the classroom code three times

Guess you like

Origin blog.csdn.net/m0_46738467/article/details/110082463