Python study notes | 5 classes and objects

Contents of this chapter: Understand classes and objects in a simple and easy-to-understand way.

All relevant codes can be viewed at https://github.com/hzyao/Python-Cookbook .
It’s wonderful to learn and practice at the same time, and to discover in time! It may taste better if eaten together!

classes and objects

In life, we can organize data by designing forms, producing forms, and filling in forms. Come! Let's compare it with the classes in the program !

  • Design form - design class (class)
  • Print form - create object
  • Fill in the form - object attribute assignment

That is to say, we can use classes to encapsulate attributes and create objects one by one based on the class for use.

1 Classes and Objects

Class usage syntax:

class 类名称:
		类的属性
		类的行为

对象 = 类名称()
"""
1. class是关键字,表示要定义类啦
2. 类的属性,即定义在类中的变量(成员变量)
3. 类的行为,即定义在类中的函数(成员方法)
"""

What exactly is the behavior (method) of a class?

class Student:
		name = None
		age = None
		
		def say_hi(self):
				print(f"嗨大家好!我是{
      
      self.name}")

Student.name = "run"
Student.age = 18

print(Student.name)
print(Student.age)

From the above we can see that not only properties can be defined in a class to record data, but also functions can be defined to record behavior. in:

  • Attributes (variables) defined in a class, we call them: member variables
  • The behavior (function) defined in the class, we call it: member method

From now on, we will call the functions defined inside the class methods !

Member method definition syntax:

Defining member methods in a class is basically the same as defining functions, but there are still subtle differences:

def 方法名(self, 形参1, ......, 形参N):
				方法体

In the parameter list of the method definition, there is a selfkeyword, which must be filledself in when the member method is defined . It is used to represent the meaning of the class object itself . When we use the class object to call a method, it will be automatically passed in by python. Within the method, if you want to access the member variables of the class, you must use .selfself

Note: selfAlthough the keyword appears in the parameter list, it does not occupy the parameter position and can be ignored when passing parameters.

class Student:
		name = None
		def say_hi(self):
				print(f"Hello 大家好 我是{
      
      self.name}")
		
		def say_hi2(self, msg):
				print(f"Hello 大家好 我是{
      
      self.name} {
      
      msg}")

stu1 = Student()
stu1.name = "run"
stu1.say_hi()                     # 调用的时候无需传参
stu1.say_hi2("很高兴认识大家!")     # 调用的时候,需要传msg参数

stu2 = Student()
stu2.name = "xmy"
stu2.say_hi()
stu2.say_hi2("嘿嘿嘿!")

When passing in parameters, selfit can be said to be transparent, ignore it! The parameters msgvary!

Therefore, the definition syntax of class and member methods is as follows:

class 类名称:
		成员变量
		
		def 成员方法(self, 参数列表):
				成员方法体

对象 = 类名称()

We have learned that the syntax for creating objects based on classes is 对象 = 类名称().

So why do we have to create an object before we can use it?

A class is just a "design drawing" within a program, and entities (that is, objects) need to be generated based on the drawing in order to work properly. This routine is what we call " object-oriented programming " - design classes, create objects based on classes, and use objects to complete specific work .

# 练习:设计一个闹钟类
class Clock:
    id = None       # 序列号
    price = None    # 价格

    def ring(self):
        print("beep")

clock1 = Clock()
clock1.id = "1220"
clock1.price = 9.99
print(f"id is {
      
      clock1.id}, price is {
      
      clock1.price}") 
clock1.ring()

clock2 = Clock()
clock2.id = "0324"
clock2.price = 8.88
print(f"id is {
      
      clock2.id}, price is {
      
      clock2.price}") 
clock2.ring()

2 Use the constructor to assign values ​​to member variables

In the previous study, we assigned values ​​​​to the properties of objects in order, which was a bit cumbersome. Actually, we can do this in a more efficient way! Assign values ​​to properties just like function parameters!

Python classes can use **__init__()**methods, called constructors .

  • It will be executed automatically when creating a class object (constructing a class) .
  • When creating a class object (constructing a class), the incoming parameters are automatically passed to the __init__ method for use .
# 构造方法的名称:__init__
class Student:
    name = None
    age = None
    tel = None      # 这些可以省略 

    def __init__(self, name, age, tel):
        self.name = name
        self.age = age
        self.tel = tel
        print("done")

stu = Student("run", 18, "0324")
print(stu.name)
print(stu.age)
print(stu.tel)

Note: The constructor is also a member method, don’t forget to provide it in the parameter list self; and when defining member variables within the constructor, you need to use keywords self.

# 练习:学生信息录入
class Student:
    def __init__(self):
        self.name = input("请输入学生姓名:")
        self.age = int(input("请输入学生年龄:"))
        self.address = input("请输入学生地址:")

for i in range(1, 11):
    print(f"当前录入第{
      
      i}位学习信息,总共需录入10位学习信息")
    stu = Student()
    print(f"学生{
      
      i}信息录入完成,信息为:【学生姓名:{
      
      stu.name}, 年龄:{
      
      stu.age}, 地址:{
      
      stu.address}】")

3 Other built-in class methods

Since these built-in class methods each have their own special functions, we call them magic methods .

There are many magic methods, let’s just understand the common ones first! For example: __init__(construction method), __str__(string method), __lt__(greater than, less than symbol comparison), __le__(greater than or equal to, less than or equal to symbol comparison), __eq__(== symbol comparison), etc.

3.1 str : string method

Function: Controls the behavior of converting classes to strings.

  • Method name:__str__
  • Return value: string
  • Content: Customize by yourself
# __str__ 字符串方法
class Student:
    def __init__(self, name, age):
        self.name = name
        self.age = age

stu = Student("run", 18)
print(stu)
print(str(stu)) # 会输出内存地址

class Student:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __str__(self):
        return f"name:{
      
      self.name}, age:{
      
      self.age}"

stu = Student("run", 18)
print(stu)
print(str(stu))

3.2 lt : <, > symbol comparison

Function: It is not possible to compare two objects directly, but by implementing __lt__the method in the class, you can complete the two comparisons at the same time: the greater than symbol and the less than symbol.

  • Method name:__lt__
  • Pass in parameters: other, another class object
  • Return value: TrueorFalse
  • Content: Customize by yourself
# __lt__ 方法
class Student:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __lt__(self, other):
        return self.age < other.age
    
stu1 = Student("run", 18)
stu2 = Student("xmy", 16)
print(stu1 < stu2) # False
print(stu1 > stu2) # True

class Student:
    def __init__(self, name, age):
        self.name = name
        self.age = age

stu1 = Student("run", 18)
stu2 = Student("xmy", 16)
print(stu1 < stu2) # 无法比较会报错

3.3 le : <=, >= symbol comparison

Function: Can be used for two comparison operators <= and >=.

  • Method name:__le__
  • Incoming parameters: other, another class object
  • Return value: TrueorFalse
  • Content: Customize by yourself
# __le__ 方法
class Student:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __le__(self, other):
        return self.age <= other.age
    
stu1 = Student("run", 18)
stu2 = Student("xmy", 16)
print(stu1 <= stu2) # False
print(stu1 >= stu2) # True

3.4 eq : == symbol comparison

Function: Can be used on the == comparison operator.

  • Method name:__eq__
  • Incoming parameters: other, another class object
  • Return value: TrueorFalse
  • Content: Customize by yourself
# __eq__ 方法
class Student:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __eq__(self, other):
        return self.age == other.age
    
stu1 = Student("run", 18)
stu2 = Student("xmy", 18)
print(stu1 == stu2) # False

Summarize:

__init__: Constructor method, which can be used to set initialization behavior when creating class objects;

__str__: Used to implement the behavior of converting class objects to strings;

__lt__: Used to compare two class objects for less than or greater than;

__le__: Used to compare two class objects for less than or equal to or greater than or equal to;

__eq__: Used to compare two class objects for equality.

Guess you like

Origin blog.csdn.net/weixin_43843918/article/details/131795124
Recommended