怎样使用条件语句来定义类?

2024-04-24 16:27:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我想生成一个class,其中输入元素的数量由TrueFalse的条件决定。我试过这样的方法

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__可能不合适。你知道吗

  • 以这种方式使用class最具python风格的方法是什么?你知道吗
  • 甚至可以使用class来实现这一点吗?你知道吗

我知道使用def函数而不是class会相当容易。你知道吗


Tags: 方法testselffalsetrue元素returninit
3条回答

不要做条件函数定义。你知道吗

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

print(Test(cond=True)(a, b, c))
# => 6

print(Test(cond=False)(a, b))
# => 3

另外,不要做if cond == True:elif cond == False:之类的比较,这也是一种反模式。如果cond应该是一个布尔值,if cond:else:是非常好的。你知道吗

我会重组你的代码。在__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

首先,避免这种情况的一种常见方法是定义一个子类。你知道吗

class Test:
    def __call__(self, a, b, c):
        return a + b + c

class Test2 (Test):
    def __call__(self, a, b):
        return a + b

result1 = Test()(a, b, c)
result2 = Test2()(a, b)

表面上看,这很难算是一种改进;但在可能在多个地方使用条件语句的情况下,这种重组可以很快得到丰厚的回报。你知道吗

相关问题 更多 >