没有'self'的Python调用方法 [英] Python calling method without 'self'

查看:133
本文介绍了没有'self'的Python调用方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我刚开始用python编程,但我不了解自我背后的全部原因。我知道它几乎像全局变量一样使用,因此可以在类中的不同方法之间传递数据。我不明白为什么在同一类中调用另一个方法时需要使用它。如果我已经在那堂课上,为什么我必须告诉它呢?

So I just started programming in python and I don't understand the whole reasoning behind 'self'. I understand that it is used almost like a global variable, so that data can be passed between different methods in the class. I don't understand why you need to use it when your calling another method in the same class. If I am already in that class, why do I have to tell it??

例如,如果我有:
为什么我需要self.thing(

example, if I have: Why do I need self.thing()?

class bla:
    def hello(self):
        self.thing()

    def thing(self):
        print "hello"


推荐答案

还可以在类 static 中创建方法,因此不需要 self 。但是,如果您确实需要它,请使用它。

Also you can make methods in class static so no need for self. However, use this if you really need that.

您的用户:

class bla:
    def hello(self):
        self.thing()

    def thing(self):
        print "hello"

静态版本:

class bla:
    @staticmethod
    def hello():
        bla.thing()

    @staticmethod
    def thing():
        print "hello"

这篇关于没有'self'的Python调用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆