社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

名称错误:python中未定义名称“run_once”

learner • 6 年前 • 1524 次点击  

巨蟒: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())
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"))

追踪:-

Traceback (most recent call last):
  File "foo/test.py", line 11, in <module>
    print(testing.run_once("test"))
  File "foo/test.py", line 7, in run_once
    run_once("").__code__ = (lambda: None).__code__
NameError: name 'run_once' is not defined
test

有人能指出哪些地方需要进行更改吗?

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/55040
文章 [ 2 ]  |  最新文章 6 年前
Umar Hayat
Reply   •   1 楼
Umar Hayat    6 年前

编写这些代码行的正确方法是:

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"))

罪魁祸首是 run_once("").__code__ = (lambda: None).__code__ 换成 testing.run_once("").__code__ = (lambda: None).__code__ exceeds the maxium limits 错误。在这种情况下,请尽量改进你的逻辑。它更多的是关于逻辑问题,而不是语法。

正确的逻辑和语法是:

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"))
Gabriel C
Reply   •   2 楼
Gabriel C    6 年前

当你定义 run_once 作为测试类中的静态方法,它必须被引用为 testing.run_once 跑一次 不存在于该类之外。

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"