python - python - 如何在不添加“self”参数的情况下在python方法中调用函数?
问题描述
我正在开发一个 Django 项目,我需要从一个方法中调用一个简单的函数:
def a():
return 1
def b():
return 2
class Report:
def calculate(self):
return self.method_to_call()
class Report1(Parent):
name = 'report 1'
description = 'report 1 desc'
method_to_call = a
class Report2(Parent):
name = 'report 2'
description = 'report 2 desc'
method_to_call = b
这不起作用,因为 python 正在将 self 参数传递给该方法。我该如何解决?我应该重新设计这个系统吗?如果是这样,这样做的正确方法是什么?我认为这个解决方案是最具可扩展性的,因为它使用了声明性语法,并且执行实际计算的代码(在另一个文件中)与定义报告及其属性(名称、描述等)的代码是分开的(在另一个文件中)
解决方案
您可以尝试将您的属性method_to_call
变成对象属性而不是类属性。
def a():
return 1
def b():
return 2
class Report:
def calculate(self):
return self.method_to_call()
class Report1(Report):
def __init__(self):
self.name = 'report 1'
self.description = 'report 1 desc'
self.method_to_call = a
class Report2(Report):
def __init__(self):
self.name = 'report 2'
self.description = 'report 2 desc'
self.method_to_call = b
print(Report1().calculate())
print(Report2().calculate())
哪个输出:
1
2
推荐阅读
- python - 获取张量的形状作为张量流中的数组
- java - 权限拒绝:重新启动应用程序时打开提供程序 com.android.providers.media.MediaDocumentsProvider
- python - 无法弄清楚如何使用 re.sub 并遍历列表
- wpf - WPF 用户控件在列表视图中使用时不支持网格比例宽度“*”
- angular - Angular 5 按钮行为不正常
- javascript - vue transition mode="out-in" 返回一个未定义的 ref 元素
- dart - 读取有状态小部件的状态
- php - 返回 json enconde 关联数组只有一项
- laravel - 找不到类“Laravel\Socialite\SocialiteServiceProvider”
- java - 难以使用 SQL 获取 Java 项目以在 Gradle 中运行