首页 > 解决方案 > 如何使用条件来定义一个类?

问题描述

我想生成一个class,其中输入元素的数量由条件确定,即Trueor False。我尝试过这样的事情

class Test:
    def __init__(self, cond):
        self.cond = cond
        if cond == True:
            def __call__(self, a, b, c):
                d1 = a + b + c
                return d1
        elif cond == False:
            def __call__(self, a, b):
                d2 = a + b
                return d2

result1 = Test(cond=True)(a, b, c)
result2 = Test(cond=False)(a, b)

但它显然不起作用,它提供了以下错误:

TypeError: 'Test' object is not callable

我怀疑我使用了错误的def,因为__init__在这种情况下可能不适合。

我知道使用def函数而不是class.

标签: python

解决方案


我会重组你的代码。__init__()添加仅用于初始化变量的条件或逻辑不是一个好主意。

相反,您应该将 dunder__call__()分开,以便可以在类实例化时调用它。

class Test:
    def __init__(self, cond):
        self.cond = cond

    def __call__(self, a, b, c=0):
        if self.cond:
            return a + b + c
        else:
            return a + b

a, b, c = 1, 2, 3

result1 = Test(cond=True)(a, b, c)
result2 = Test(cond=False)(a, b)

print(result1)  # 6
print(result2)  # 3

推荐阅读