条件的连锁类方法

发布于 2025-02-13 19:35:40 字数 1103 浏览 2 评论 0原文

想象一下,我有以下简化的类:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

杀お生予夺 2025-02-20 19:35:40

您可以做这样的事情:

instance.method_1().__getattribute__("method_2" if dummy_condition else "method_3")()

这是利用__ getAttribute __ dunder然后调用它

You can do something like this instead:

instance.method_1().__getattribute__("method_2" if dummy_condition else "method_3")()

This utilises __getattribute__ dunder then calls it

久夏青 2025-02-20 19:35:40

您应该使用__ getAttribute __魔术方法。您可以根据其实例的名称(str)获得一个属性。

__ getAttribute __

无条件地呼叫以实现实例的属性访问
班级。如果课程也定义 getAttr (),后者将
除非 getAttribute ()要么明确称呼它或
提出一个属性。此方法应返回(计算)
属性值或提高属性异常。为了
避免使用这种方法中的无限递归,其实施应
始终以相同名称调用基类方法以访问任何
它需要的属性,例如对象。 getAttribute (self,name)。

参考:

代码:

class ExampleClass:
    def __init__(self, input_1):
        self.input_1 = input_1

    def method_1(self):
        print("METHOD_1")
        return self

    def method_2(self):
        print("METHOD_2")
        return self

    def method_3(self):
        print("METHOD_3")
        return self


instance = ExampleClass("Hello")

dummy_condition = True

instance.method_1().__getattribute__("method_2" if dummy_condition else "method_3")()

输出:

>>> python3 test.py 
METHOD_1
METHOD_2

输出如果dummy_condition = false

>>> python3 test.py 
METHOD_1
METHOD_3

You should use the __getattribute__ magic method. You are able to get an attribute of your instance based on name (str) of its.

__getattribute__:

Called unconditionally to implement attribute accesses for instances
of the class. If the class also defines getattr(), the latter will
not be called unless getattribute() either calls it explicitly or
raises an AttributeError. This method should return the (computed)
attribute value or raise an AttributeError exception. In order to
avoid infinite recursion in this method, its implementation should
always call the base class method with the same name to access any
attributes it needs, for example, object.getattribute(self, name).

Reference:

Code:

class ExampleClass:
    def __init__(self, input_1):
        self.input_1 = input_1

    def method_1(self):
        print("METHOD_1")
        return self

    def method_2(self):
        print("METHOD_2")
        return self

    def method_3(self):
        print("METHOD_3")
        return self


instance = ExampleClass("Hello")

dummy_condition = True

instance.method_1().__getattribute__("method_2" if dummy_condition else "method_3")()

Output:

>>> python3 test.py 
METHOD_1
METHOD_2

Output if dummy_condition = False:

>>> python3 test.py 
METHOD_1
METHOD_3
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文