python - 在类范围内的函数但不在类 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
很明显,我没有在正确的地方定义函数。如果这是一个已经回答过的相当基本的问题,我深表歉意,我搜索并找不到答案。
解决方案
在我看来,您想使用静态方法。
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
推荐阅读
- java - java中的通用接口继承
- java - 如何在java中根据列(升序)对二维数组进行排序
- django - 使用 Django ORM 预取间接相关的项目
- laravel - 使用 api 将数据更新到数据库 laragon
- javascript - 在哪里从服务器加载数据以获得更快的结果?
- c - 是否有一个函数可以在 C 中获取文件流中的行数?
- java - 实际数组为空 - JUnit
- rabbitmq - spring amqp 默认启用重试并根据指定异常阻止
- node.js - 在 socket.io 中建立连接时用户对象未更新
- tensorflow - 张量流 2.0.0-alpha0 版本中废弃函数的问题