社区所有版块导航
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 年前 • 1525 次点击  

巨蟒: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 年前