Python learning [classes and objects]

foreword

Happy Labor day!
In the previous article python learning - [the eighth bullet] , I introduced the functions in python, and this article continues to learn the functions in pythonclasses and objects

insert image description here

We know that everything in python is an object. Before starting this article, let's take a look at the two camps in the programming world——procedural and object oriented.
We must have heard these two terms a lot, so let’s briefly introduce what is process-oriented and object-oriented, and what is the difference and connection between the two.

process oriented

Process-oriented : things are relatively simple, you can uselinearThinking to solve it; for example - if our guests come to our house as guests, we want to treat them to dinner, how many steps should we take to make a good dish? We use linear thinking to consider whether it should be divided into three steps: buying vegetables, washing vegetables, and cooking vegetables, which are represented by flow charts:

insert image description here

object oriented

Object-oriented : Things are more complicated and cannot be explained using simple linear thinking.
Let’s still take the example of treating guests to dinner: if a guest comes to visit, we just don’t know how to cook. At this time, we can open the mobile phone ordering app, choose the meal we want to order through the app, and then ask the courier brother to deliver the meal:

insert image description here

difference and connection

Through these two examples, we found that process-oriented we need to implement step by step; and through object-oriented , 我们只需要创建一个包含实现指定功能和方法、具有指定属性的类calling these methods by instantiating objects one by one or calling these methods directly with classes can help us achieve the desired effect .
insert image description here

The process-oriented way of thinking focuses 关注程序如何执行on how to be organized and separated into modules for higher-level abstraction and reuse. Therefore, in 微观操作方面China, process-oriented may be the most suitable approach because it emphasizes strict sequence and flow control.
However, in implementation 整个程序的过程中, some more advanced programming paradigms (such as object orientation ) may be more suitable for modular code and 提高代码可重用性和可维护性.

In fact, we have been exposed to many methods in the past python learning. For example, in the learning list, we will use the append() method to add an element to the list. This appen() method is a common method in the list class. method:
insert image description hereinsert image description here

Class composition and creation

class composition

The composition of a class includes: class attributes instance methods static methods class methods

class creation

Class definition syntax: class Class_name: Among them, Class_name is the name of the class (class name), consisting of one or more words, and the first letter of each word is capitalized .

class  Class_name:
	pass

instance object creation

A class can create multiple instance objects of this class, and the attribute values ​​of each instance object can be different or the same, andThe authority of the instance object is the largest. After creating an instance object, you can call instance methods or class attributes through this instance object.
Instance object creation syntax: instance object name = class name (parameter)
If no static variables are passed in the class, the creation of the instance object here does not require parameter passing. (When the instance object is created, Python will automatically allocate space for it, and call the __init__ method of the class to perform initialization operations. If no parameters are defined, no parameters need to be passed.)

class Student:
    pass
stu1=Student(参数1,参数2,参数3,。。。)
stu2=Student(参数1,参数2,参数3,。。。)
stuN=Student(参数1,参数2,参数3,。。。)

insert image description here

The id value of the instantiated object is converted into hexadecimal and the value is the same , here: stu1id value: 140203633998736 converted into hexadecimal is equal to its value 7f83b3ccfb90
stu1=Student('tom',20) #In the init method we Two parameters of name and age are passed in, and the parameters of the instance object created here are also two
print(id(stu1),type(stu1)) #140203633998736 <class ' main .Student'>
print(stu1) #< main .Student object at 0x7f83b3ccfb90> id is converted to hexadecimal and the output value of stu1 is the same

class attribute

Class attributes: Variables outside methods in a class are called class attributes, and class attributes are shared by all objects of the class.
Call method of class attribute:
1: It can be called by instance object , the syntax is instance object name. attribute

2: It can be called directly by class , the syntax is class name. class attribute

class Place:
    # 类属性
    place1='山东'
    place2='河南'
#pl1和pl2分别为该类的实例对象
pl1=Place()
pl2=Place()
print('----------类属性的使用------------------\n')
#实例对象调用
print('出生地1:',pl1.place1,id(pl1.place1))
print('出生地2:',pl1.place2,id(pl1.place2))
print('直接被类调用:',Place.place1,Place.place2)
'''
出生地1: 山东 140018104483248
出生地2: 河南 140018103789008
直接被类调用: 山东 河南
'''

print('\n----------在类外使用类改变类属性-------\n')
# 类属性:place1和place2  被该类的所有实例对象(这里是pl1和pl2)所共享,
#因此在类外将类属性改变后,用该类的所有实例对象调用该类属性时,类指针指向的地址都是类属性改变后的地址
Place.place1='河北'
print('出生地1:',pl1.place1,id(pl1.place1))
print('出生地2:',pl2.place1,id(pl2.place1))
'''
 出生地1: 河北 140314679194608
 出生地2: 河北 140314679194608
'''

We see that after changing the class attribute outside the class, when the instance object is used to call this type of attribute again, what is printed out is 类属性改变后的值, let's take a look at the memory map:

insert image description here
It can be seen intuitively that there is a class pointer in each instance object , pointing to the class , then when we change the address pointed to by a certain class attribute, what is printed out when the instance object calls this attribute is the changed class attribute memory address.

Init method in class

The initialization method in Python is the first method called when an object is created, and is used to initialize the properties of the object. Typically, the initialization method is implemented as the __init__() method. Its format is def__init__(self):

Among them, the method name is composed of init (abbreviation for initialize, meaning initialization) plus double underscores on the left and right sides.
When doing the initialization method,Need to pass in a parameter self(self is a conventional variable name used to represent the instance object itself. Although you can choose other names as the self parameter, generally follow this convention to ensure that the code is easy to read and understand.), ; in the method of the class (such as 在python的类中 self代表实例本身,具体来说,是该实例方法的内存地址__init__ ), the first parameter is always self,表示创建的类的实例本身,而不是类本身。
The initialization method is automatically executed whenever the class is instantiated,for example:

insert image description here
You can see: we just created an instance object, and did not call the init method, it was executed automatically. Using this feature, we usually complete the setting of the initial value of the class attribute in the initialization method .

class Student  :
    #类属性
    place='山东' 
    school='大学'
    # 初始化方法  
    def __init__(self,name,age):
        self.name=name #self.name  称为实例属性 进行一个赋值操作  将局部变量的name的值赋给实例属性
        self.age=age

We passed in two parameters name and age in the initialization method. At this time, they are only local variables . If they want to be called by the instance object, 需要在初始化方法中将局部变量分别赋给实例属性the instance attribute here is self.name , and of course it can also be self. Alias , just We are used to using the names of local variables, which also has a certain degree of readability.

When we pass in parameters when we create an instance object of a class, we need to initialize the method in the class body and pass in relevant parameters.

Here we briefly understand the self parameter in python:

1.self只有在类的方法中才会有 , 其他函数或方法是不必带self的。

2.在调用时不必传入相应的参数。

3.在类的方法中(如__init__)  , 第一参数永远是self , 表示创建的类实例本身 , 而不是类本身。

4.可以把对象的各种属性绑定到self。

5.self代表当前对象的地址。self能避免非限定调用造成的全局变量。

6.self不是python的关键字, 也可以用其他名称命名 , 但是为了规范和便于读者理解 ,  推荐使用self。

7:python中的self等价于C++中的self指针和Java、C#中的this参数。

8:如果不加self ,  表示是类的一个属性(可以通过"类名.变量名"的方式引用), 加了self表示是类的实例的一个属性(可以通过"实例名.变量名"的方式引用)

instance method

A function defined in a class is called a method, which is equivalent to a function outside the class. The method can have certain functions and be executed after being called.
The biggest feature of an instance method is that it must contain at least one self parameter, which is used to bind the instance object calling this method (Python will automatically complete the binding).

Invocation of the instantiation method:

1: Use the instance object call: instance object name. method name ()

2: Use the class call: class name. instance method name (instance object name)

class Student:
    place='山东'  #类属性   直接写在类里的变量  叫做类属性
    school='大学'

    # 初始化方法
    def __init__(self,name,age):
        self.name=name
        self.age=age

# 实例方法  定义在类外面的函数叫做函数;定义在类里面的函数叫做方法
#  其中info()括号中可以不写东西,但是默认是存在self的,习惯上写上self
    def info(self):
        print('我的名字叫:',self.name,'年龄是:',self.age)
    def eat(self):
        print('吃东西')
    def drink():
        print('喝水')
# 创建实例对象
stu1=Student('tom',20)
 
print('\n----------------使用实例对象调用实例方法------------\n')

# 创建完成实例对象,就可以通过这个实例对象调用实例方法  对象名.方法名
stu1.eat()
stu1.info()
stu1.drink()
'''
吃东西
我的名字叫: tom 年龄是: 20
喝水
'''

print('\n-----------------通过Student类来调用实例方法-----------\n')
# 或者是通过Student类进行实例方法的调用    类名.方法名(对象名)
Student.eat(stu1)
Student.info(stu1)
Student.drink()
'''
吃东西
我的名字叫: tom 年龄是: 20
喝水
'''

If no parameters are written in the instance method, there is no need to pass in the instance object when calling the instance method with the class; if passed in, a TypeError: drink() takes 0 positional arguments but 1 was given error will be thrown

insert image description here
insert image description here

class method

Class method: A method decorated with the decorator @classmethod within the class, directly accessed using the class name.

A Python class method is similar to an instance method. It must contain at least one parameter, but it is usually named cls in a class method , and Python will automatically bind the class itself to the cls parameter (note that the binding is not a class object). That is to say, when we call the class method, we don't need to explicitly pass parameters for the cls parameter.

Class method call:

​1: Use the class name: class name. class method name ()

2: Use the instance object: instance object name. class method name ()

# 类方法的使用
class Staff:
    # 类方法
    @classmethod
    def class_method(cls):
        print('我是一个类方法')
staff1=Staff()
staff2=Staff()
print('------------类方法的使用-----------\n')
Staff.class_method()
print('----------实例对象调用类方法------\n')
staff2.class_method()

insert image description here

If there is no @classmethod, the Python interpreter will recognize the class_method() method as an instance method, not a class method.

insert image description here

static method

Static method: In fact, it is the function we have learned. The only difference from the function is that the static method is defined in the space of the class (class namespace), while the function is defined in the space where the program is located (global namespace), that is, the class in vitro.

A static method has no special parameters like self, cls, so the Python interpreter will not do any class or object binding for the parameters it contains. Because of this, any class attributes and class methods cannot be called in the static methods of the class.

Static method: The method modified with @staticmethod can be directly accessed using the class name.

Static method call:

1: Use the class name: class name. static method name ()

2: Use the instance object: instance object name. static method name ()

# 静态方法的使用
class Workers:
    @staticmethod
    def static_method():#静态方法中没有默认参数
        print('我是一个静态方法')
worker1=Workers()
print('-----------使用类调用静态方法-----------\n')
Workers.static_method()
print("----------使用实例对象调用静态方法-----------\n")
worker1.static_method()

insert image description here

Summarize

In actual programming, class methods and static methods are almost never used, because we can use functions instead of them to achieve the desired functions, but in some special scenarios (such as in factory mode), class methods and static methods are still used static method.

one word per article

Hearing other people's stories a thousand times is worse than doing one thing yourself.

If there are any deficiencies, thanks for correcting!

Guess you like

Origin blog.csdn.net/weixin_64122448/article/details/130443925