对于Python中self的看法

首先看一段Java代码

public class Test {
    public String name;
    public int  age;
    public String gender;
    
    public String color;
    
    public Test(String name,int  age,String gender){
        this.name=name;
        this.age=age;
        this.gender=gender;
    }
    
    public void setClolor(){
        this.color=this.getColor();  //this代表的是当前的实例
        //或者
        color=getColor();//但是this是隐式的,可以不写
    }
    
    public String getColor(){
        return "withe";
    }
}

从上面的Java代码可以看出,this代表的是当前实例,也就是正在调用Test类方法中的实例,但是在Java中,this是隐式的,可以不写

然后再看一段Python代码

class Food:
    eatWhat="";
    def __init__(self,eatWhat):
        self.eatWhat=eatWhat;
    def eatfood(self):
        self.eatWhat="apple"
    
    def findfood(self):
        print "找到食物了"
        self.eatfood()
    

可以看到,在Python中,self实际上和Java中的this效果是一样的,代表的是当前的实例本身,但是如果在方法调用或者是给成员变量赋值的时候不写self来调用会报错,说明 self 在Python中是显式的,必须要写self才能调用自身的方法,这和Java

中this是隐式的是有所不同的。

原文地址:https://www.cnblogs.com/dacai/p/5241329.html