gpt4 book ai didi

没有 'self'的Python调用方法

转载 作者:IT老高 更新时间:2023-10-28 22:12:23 25 4
gpt4 key购买 nike

所以我刚开始用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com