python - 如何使用条件来定义一个类?
问题描述
我想生成一个class
,其中输入元素的数量由条件确定,即True
or 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__
在这种情况下可能不适合。
- 以这种方式使用 a 的最pythonic方式是
class
什么? - 甚至可以使用 a 来做到这一点
class
吗?
我知道使用def
函数而不是class
.
解决方案
我会重组你的代码。__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
推荐阅读
- css - 如何在不影响其他媒体查询的情况下进行媒体查询
- java - @After 和 @Before 注释没有执行第二种方法
- macos - Mac Automator AppleScript:如果剪贴板以定义的字符串开头,则修改剪贴板以删除指定的字符
- python - 为什么修改函数内另一个列表的副本的列表会影响原始列表?
- c# - 我如何知道我在 caspol 的特定文件夹中拥有的权限?
- .net - Mollie v2 .NET 库创建和检查付款请求的状态
- sql - 通过跳过空值来比较列值?
- vuejs2 - 在发生其他任何事情之前检索文件
- azure-functions - 队列消息在 -poison 队列中结束
- javafx - 转换翻译 JavaFX 行