首页 > 解决方案 > 在类范围内的函数但不在类 python 上执行

问题描述

我正在编写一个类来从 API 获取数据。我有我想在课堂上执行的功能,例如

self.do_this()

我也有应该在该功能内做事的功能,例如

def do_this_part(response):
    Dict = {}
    for key, value in response.items():
        Dict[key] = value
    return Dict

我想在类中有一个更小的函数,以便它总是在类中。它永远不会在类上执行,但将在将在类中执行的多个函数中执行。

我收到以下错误:

NameError: name 'do_this_part' is not defined

很明显,我没有在正确的地方定义函数。如果这是一个已经回答过的相当基本的问题,我深表歉意,我搜索并找不到答案。

标签: pythonfunctionclassnameerror

解决方案


在我看来,您想使用静态方法。

class C:
    def do_this(self):
        response = {}
        self.do_this_part(response)

    @staticmethod
    def do_this_part(response):
        Dict = {}:
        for key, value in response.items():
            Dict[key] = value
        return Dict

推荐阅读