行者孙Python

铸器篇-Day71 self 关键字详解

📖 知识点

self 核心定义

  1. 在实例方法(包括__init__构造方法)的第一个形参,约定名字叫self,你也可以改成别的名字,但行业惯例统一用 self。

  2. 当对象调用方法时,Python自动把调用这个方法的对象,传递给 self,不需要手动传参。

  3. self.属性 / self.方法():访问当前这个实例自己的属性和方法。

示例代码

 

class Student:
    def __init__(self, name):
        # self 就是即将创建的这个学员对象
        self.name = name

    def say_hello(self):
        # self 就是调用say_hello的那个stu对象
        print(f"你好,我是 {self.name}")

stu1 = Student("小明")
stu1.say_hello()

 

执行 stu1.say_hello(),Python 底层等价于:

 

Student.say_hello(stu1)

 

自动把 stu1 传给 self!

关键要点

  1. self 只是参数名字,换成this_obj也能跑,但是所有人都写 self,不要改名字。

  2. 同一个类,多个对象调用方法:

    • stu1.say_hello() → self = stu1

    • stu2.say_hello() → self = stu2

  3. 方法内部,不加 self 的变量,只是方法内部的局部变量,不属于对象,出了方法就消失。

 

def say_hello(self):
    word = "hi" # 局部变量,只在这个函数内有效
    print(word, self.name) # self.name才是对象属性

 

⚠️ 高频坑忘记写 self,直接写 name,程序会去寻找局部变量 name,而不是对象属性,大概率报 NameError。

⚔️ Kata 实战任务

任务需求:

  1. 定义 Student 类

  2. __init__接收 name,绑定self.name

  3. 编写实例方法 introduce(),打印 我是{self.name}

  4. 创建 stu1=Student ("小李"),stu2=Student ("小张")

  5. 分别调用 introduce,观察 self 分别绑定不同对象

参考代码

 

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

    def introduce(self):
        # self 自动绑定调用该方法的对象
        print(f"self指向当前对象,我是:{self.name}")


stu1 = Student("小李")
stu2 = Student("小张")

stu1.introduce()
stu2.introduce()

 

运行输出:

 

self指向当前对象,我是:小李
self指向当前对象,我是:小张

 

🧠 思考题

  1. 调用 stu1.introduce() 的时候,我们括号里面没有传参数,self 的值是谁给的?

  2. 如果把方法的第一个参数改成me,代码还能不能正常运行?试写代码验证。

‹ 返回目录
🏠首页 Python 📦资源 👤关于我