zoukankan      html  css  js  c++  java
  • 对于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是隐式的是有所不同的。

  • 相关阅读:
    Springsecurity3.1.3配置多个登陆页面
    将数字转换为大写(保留小数点后面2位)
    纯JavaScript实现的二维码图片生成器
    poi导出excel
    发送邮件
    Lodop实现打印功能
    遍历list
    循环监听输入框回车事件
    监听回车事件记录
    简单的事务操作过程
  • 原文地址:https://www.cnblogs.com/dacai/p/5241329.html
Copyright © 2011-2022 走看看