条件的连锁类方法
想象一下,我有以下简化的类:
class ExampleClass:
def __init__(self, input_1):
self.input_1 = input_1
def method_1(self):
# Do something
return self
def method_2(self):
# Do something
return self
def method_3(self):
# Do something
return self
instance = ExampleClass('Hello')
如果我想顺序调用这些方法,我可以简单地链接它们:
instance \
.method_1() \
.method_2() \
.method_3()
现在想象我也有一个条件,如果评估到true,则应调用method> method_2()
,否则调用Method_3()
。 我可以通过写作来实现这一目标:
dummy_condition = True
instance.method_1()
if dummy_condition:
instance.method_2()
else:
instance.method_3()
问题:使用方法链方法如何执行此逻辑,而无需太多的详细代码?我尝试发挥创造力,并提出以下内容,不幸的是,这是不起作用的:
instance \
.method_1() \
(.method_2() if dummy_condition else .method_3())
有什么想法吗?
Imagine I have the following simplified class:
class ExampleClass:
def __init__(self, input_1):
self.input_1 = input_1
def method_1(self):
# Do something
return self
def method_2(self):
# Do something
return self
def method_3(self):
# Do something
return self
instance = ExampleClass('Hello')
If I wanted to call the methods sequentially, I could simply chain them as such:
instance \
.method_1() \
.method_2() \
.method_3()
Now imagine I also have a condition, that if evaluates to true, should call method_2()
, otherwise call method_3()
.
I can achieve this by writing:
dummy_condition = True
instance.method_1()
if dummy_condition:
instance.method_2()
else:
instance.method_3()
Question: How can I perform this logic without so much verbose code, using method chaining instead? I have tried being creative, and came up with the following, which unfortunately doesn't work:
instance \
.method_1() \
(.method_2() if dummy_condition else .method_3())
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以做这样的事情:
这是利用
__ getAttribute __
dunder然后调用它You can do something like this instead:
This utilises
__getattribute__
dunder then calls it您应该使用
__ getAttribute __
魔术方法。您可以根据其实例的名称(str)获得一个属性。__ getAttribute __
:参考:
代码:
输出:
输出如果
dummy_condition = false
:You should use the
__getattribute__
magic method. You are able to get an attribute of your instance based on name (str) of its.__getattribute__
:Reference:
Code:
Output:
Output if
dummy_condition = False
: