NameError:python中未定义名称“run_once”
Python:3.8.1 我只想在班上运行一次方法。我已经学会了以下实现目标的方法,并且工作得很好NameError:python中未定义名称“run_once”,python,Python,Python:3.8.1 我只想在班上运行一次方法。我已经学会了以下实现目标的方法,并且工作得很好 def run_once(): # Code for something you only want to execute once print("test") run_once.__code__ = (lambda: None).__code__ return "Success" print(run_once()) print(run_once()) prin
def run_once():
# Code for something you only want to execute once
print("test")
run_once.__code__ = (lambda: None).__code__
return "Success"
print(run_once())
print(run_once())
print(run_once())
输出:-->预期和实际
test
Success
None
None
很明显,在试图通过类中的静态方法实现相同的操作时出错
class testing():
@staticmethod
def run_once(data):
# Code for something you only want to execute once
print(data)
run_once("").__code__ = (lambda: None).__code__
return "Success"
print(testing.run_once("test"))
回溯:-
是否有人可以突出显示需要进行更改的位置?当您将run\u once定义为测试类内部的静态方法时,必须将其引用为testing.run\u once,因为run\u once不存在于该类外部
类别测试:
@静力学方法
def运行数据:
只想执行一次的代码
打印数据
测试。运行一次。\uuuu代码\uuuu=lambda x:None。\uu代码__
回归成功
编写这些代码行的正确方法是:
class testing():
@staticmethod
def run_once(data):
# Code for something you only want to execute once
print(data)
testing.run_once("").__code__ = (lambda: None).__code__
return "Success"
print(testing.run_once("test"))
罪魁祸首行运行一次。\uuuuuu代码\uuuuu=lambda:None.\uuuu代码\uuuu将被替换为测试。运行一次。\uuuu代码\uuuu=lambda:None.\uuu代码\uu。但是,它也不能解决问题,因为现在您正在类中调用类函数,这将导致超出最大限制的错误。在这种情况下,请尽量改进你的逻辑。它更多的是关于逻辑问题,而不是语法
正确的逻辑和语法如下:
class testing():
@staticmethod
def run_once(data):
# Code for something you only want to execute once
print(data)
testing.run_once.__code__ = (lambda x: None).__code__
return "Success"
print(testing.run_once("test"))
您必须始终将静态方法称为testing.run_,因此更改第7行。这是因为一旦定义在类中,run_once就不会在全局范围中定义。您可以通过更简单的方法实现相同的目标,例如使用函数变量和简单的if语句来测试它。
class testing():
@staticmethod
def run_once(data):
# Code for something you only want to execute once
print(data)
testing.run_once.__code__ = (lambda x: None).__code__
return "Success"
print(testing.run_once("test"))