Skip to main content
 首页 » 编程设计

python之在 python 中进行函数链接时,有没有办法引用 "current"对象

2025年02月15日12Renyi-Fan

假设我得到了以下类(class):

class foo(object): 
 
    def __init__(self, int): 
        self.count = int 
 
    def increment(self, int): 
        return foo(int + 1) 
 
    def decrement(self, int): 
        return foo(int - 1) 

我的目标是将函数调用链接在一起以获得我想要的结果,而不必将每个对象分配给一个变量。例如,我知道我可以这样做:

obj = foo(0) 
obj = obj.increment(obj.count) 
obj = obj.decrement(obj.count) 
obj = obj.increment(obj.count) 
obj = obj.decrement(obj.count) 
print obj.count 
0 

但我希望能够做到这一点:

finalcount = obj(0).increment(?.count).decrement(?.count) 

但我不知道是否可以用某些东西代替 ? 来引用正在调用其方法的对象,因为该对象尚未分配名称。

请您参考如下方法:

您的对象在您当前的代码中并没有真正贡献任何东西。请注意您的类中的方法如何不引用任何对象状态 — 它们从不使用 self。更好的办法是完全省略 int 参数,而使用 self.count 代替:

class foo(object): 
    def __init__(self, int): 
        self.count = int 
 
    def increment(self): 
        return foo(self.count + 1) 
 
    def decrement(self): 
        return foo(self.count - 1) 

然后,你想写的变成这样:

finalcount = foo(0).increment().decrement() 

但是,要回答您最初的问题,无法在调用链中引用“当前”对象。如果要引用中间对象,则必须将其分配给变量。