Python 系列01 Python里面self的用法

Python里的self 和 Java里的this

从我一开始接触python,就对self这个函数很疑惑。可能因为之前写Java比较多,想当然的用写Java的思路写Python,把python中的"self"理解成Java中的"this"。

但Java并没有将"This" 这个关键字作为一个函数的构造参数。this只有调用内部方法的时候才会使用到,并且无需提前声明。如下代码:

Java 复制代码
public class Parent {
    // 类变量(静态变量)
    public static String parentClassVariable = "Parent Class Variable";
    // 实例变量
    private String name;
    // 父类的构造函数
    public Parent(String name) {
        this.name = name;  // 初始化实例变量
        System.out.println("Parent constructor called with name: " + name);
    }
    // 父类的一个普通方法
    public void display() {
        System.out.println("Display method in Parent class");
        System.out.println("Name: " + this.name);  // 访问实例变量
        System.out.println("Parent Class Variable: " + Parent.parentClassVariable);  // 访问类变量
    }
    // 父类的静态方法
    public static void staticDisplay() {
        System.out.println("Static Display method in Parent class");
        System.out.println("Parent Class Variable: " + parentClassVariable);  // 访问类变量
    }
}

反观python:几乎所有函数里面都有"self" 这个参数。

python 复制代码
class Parent:
    # 类变量(静态变量)
    parent_class_variable = "Parent Class Variable"

    def __init__(self, name):  # 父类构造函数
        self.name = name  # 实例变量
        print(f"Parent constructor called with name: {name}")

    def display(self):  # 父类的实例方法
        print("Display method in Parent class")
        print(f"Name: {self.name}")  # 访问实例变量
        print(f"Parent Class Variable: {Parent.parent_class_variable}")  # 访问类变量

    @staticmethod
    def static_display():  # 父类的静态方法
        print("Static Display method in Parent class")
        print(f"Parent Class Variable: {Parent.parent_class_variable}")  # 访问类变量

后面问了问kimi,也查了一些资料才知道:

1. 类的方法中必须使用 self

当函数定义在类中,并且作为类的方法 被调用时,self 是必须的。self 是类实例的引用,用于访问实例的属性和其他方法。

2. 普通函数中不需要 self

如果函数定义在类之外,或者不是类的方法,那么不需要使用 self。这种函数被称为普通函数,它与类实例无关。

python 复制代码
def normal_function(x, y):
    return x + y

result = normal_function(3, 4)  # 输出 7

继承的写法

Python 继承示例:显式写法 vs 隐式写法

1. 定义父类
python 复制代码
class Parent:
    def __init__(self, name):
        print(f"Parent constructor called with name: {name}")
        self.name = name

    def display(self):
        print(f"Parent display method called. Name: {self.name}")
2. 子类实现:显式写法
python 复制代码
class ChildExplicit(Parent):
    def __init__(self, name, age):
        super(ChildExplicit, self).__init__(name)  # 显式调用父类构造函数
        self.age = age
        print(f"ChildExplicit constructor called with age: {age}")

    def display(self):
        super(ChildExplicit, self).display()  # 显式调用父类方法
        print(f"ChildExplicit display method called. Age: {self.age}")
3. 子类实现:隐式写法
python 复制代码
class ChildImplicit(Parent):
    def __init__(self, name, age):
        super().__init__(name)  # 隐式调用父类构造函数
        self.age = age
        print(f"ChildImplicit constructor called with age: {age}")

    def display(self):
        super().display()  # 隐式调用父类方法
        print(f"ChildImplicit display method called. Age: {self.age}")
4. 测试代码
python 复制代码
if __name__ == "__main__":
    print("=== 测试显式写法 ===")
    child_explicit = ChildExplicit("John", 10)
    child_explicit.display()
    print()

    print("=== 测试隐式写法 ===")
    child_implicit = ChildImplicit("Alice", 15)
    child_implicit.display()
相关推荐
IT猿手2 小时前
基于强化学习 Q-learning 算法求解城市场景下无人机三维路径规划研究,提供完整MATLAB代码
神经网络·算法·matlab·人机交互·无人机·强化学习·无人机三维路径规划
万能程序员-传康Kk5 小时前
旅游推荐数据分析可视化系统算法
算法·数据分析·旅游
PXM的算法星球5 小时前
【并发编程基石】CAS无锁算法详解:原理、实现与应用场景
算法
ll7788115 小时前
C++学习之路,从0到精通的征途:继承
开发语言·数据结构·c++·学习·算法
烨然若神人~5 小时前
算法第十七天|654. 最大二叉树、617.合并二叉树、700.二叉搜索树中的搜索、98.验证二叉搜索树
算法
爱coding的橙子5 小时前
每日算法刷题Day2 5.10:leetcode数组1道题3种解法,用时40min
算法·leetcode
程序媛小盐6 小时前
贪心算法:最小生成树
算法·贪心算法·图论
Panesle6 小时前
分布式异步强化学习框架训练32B大模型:INTELLECT-2
人工智能·分布式·深度学习·算法·大模型
多多*6 小时前
算法竞赛相关 Java 二分模版
java·开发语言·数据结构·数据库·sql·算法·oracle
逐光沧海6 小时前
数据结构基础--蓝桥杯备考
数据结构·c++·算法·蓝桥杯