首页 > 解决方案 > 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 参数传递给该方法。我该如何解决?我应该重新设计这个系统吗?如果是这样,这样做的正确方法是什么?我认为这个解决方案是最具可扩展性的,因为它使用了声明性语法,并且执行实际计算的代码(在另一个文件中)与定义报告及其属性(名称、描述等)的代码是分开的(在另一个文件中)

标签: pythonfunctionmethodsarchitecture

解决方案


您可以尝试将您的属性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

推荐阅读