所以我刚开始用 python 编程,我不明白“self”背后的全部原因。我知道它几乎就像一个全局变量一样使用,因此可以在类中的不同方法之间传递数据。我不明白为什么在同一个类中调用另一个方法时需要使用它。如果我已经在那个类,我为什么要告诉它??
例如,如果我有: 为什么我需要 self.thing()?
class bla:
def hello(self):
self.thing()
def thing(self):
print "hello"
最佳答案
你也可以在类static
中创建方法,所以不需要self
。但是,如果您确实需要,请使用它。
你的:
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调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18679803/