我正在开发一个 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 参数传递给方法。我该如何解决?我应该重新设计这个系统吗?如果是这样,这样做的正确方法是什么?我认为这个解决方案是最具扩展性的,因为它使用了声明式语法,并且执行实际计算的代码(在另一个文件中)与定义报告及其属性(名称、描述等...)的代码分开了/p>
答案 0 :(得分:1)
您可以尝试将您的属性 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
答案 1 :(得分:1)
您可以将 calculate()
设为类方法:
def a():
return 1
def b():
return 2
class Report:
@classmethod
def calculate(cls):
return cls.method_to_call()
class Report1(Report):
name = 'report 1'
description = 'report 1 desc'
method_to_call = a
class Report2(Report):
name = 'report 2'
description = 'report 2 desc'
method_to_call = b
print(Report1.calculate())
print(Report2.calculate())
这给出:
1
2