3

Python中self类似Java中是this吗?

 8 months ago
source link: https://www.jdon.com/71358.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Python中self类似Java中是this吗?

在 Python 中,self 类似于 Java 中的 this。

Python 中的 self 和 Java 中的 this 都是对调用方法的对象实例的引用。

在 Python 中,self 是类中实例方法中第一个参数的常规名称。它代表方法被调用对象的实例。

class MyClass:
    def __init__(self, value):
        self.value = value

def display(self):
        print(f"Value: {self.value}")

# 创建 MyClass 实例
obj = MyClass(42)

# 使用 self 调用显示方法
obj.display()  # Output: Value: 42

在 Java 中,这也有类似的作用:

public class MyClass {
    private int value;

public MyClass(int value) {
        this.value = value;
    }

public void display() {
        System.out.println("Value: " + this.value);
    }

public static void main(String[] args) {
        // Creating an instance of MyClass
        MyClass obj = new MyClass(42);

// 使用this方法调用显示方法
        obj.display();  // Output: Value: 42
    }
}

在这两种情况下,self 和 this 都用来指类中当前对象的实例变量和方法。它们有助于区分同名的实例变量和参数或局部变量,从而明确哪些变量或方法与被操作的对象相关联。

在这两种情况下,Python 中的 self 和 Java 中的 this 有着相同的作用--它们都被用作调用方法的对象实例的引用。它们允许您访问类中的实例变量和方法,将它们与同名的局部变量或参数区分开来。在 Python 中使用 self 而在 Java 中使用 this 反映了特定语言的习惯。

Python中星号 * 的七种用法

在 Python 中,星号 (*) 根据上下文有多种用途。以下是 Python 中星号的一些常见用法: .

为什么Python很糟糕

作者对Python语言的批评。作者认为Python的流行导致了行业的滞后: .

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK