【问题标题】:How to call a function inside a method in python without the 'self' argument being added?python - 如何在不添加'self'参数的情况下在python方法中调用函数?
【发布时间】:2021-02-22 14:03:34
【问题描述】:

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

【问题讨论】:

  • 很难理解你的情况。 Django 遵循一些特定规则,您的示例可能不一定有效。您可以探索的一个选项是模型管理器
  • 如果您希望Report1Report2 实现自己的calculate 方法,您可以这样做。他们可以从Report 继承并定义自己的calculate - 你不需要在Report 中使用它,它会包含所有常见的东西。
  • @JohnLyon 我在想这个,但如果“计算”中的代码位于另一个文件中,它看起来更干净。

标签: python function methods architecture


【解决方案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

【讨论】:

  • 这对我帮助很大。我所做的是在父类中定义一个 init 方法并设置self.value_method = self.__class__.value_method。所有其他属性都可以在此方法之外定义,没有问题。
【解决方案2】:

您可以将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

【讨论】:

  • 这很棒,它甚至可以使用“@property”并且需要最少的代码。
猜你喜欢
  • 2018-07-13
  • 1970-01-01
  • 2012-11-10
  • 1970-01-01
  • 1970-01-01
  • 2023-03-07
  • 1970-01-01
  • 2021-12-04
相关资源
最近更新 更多