python 中的链接实例方法

Chaining instance methods in python

我想用方法和子方法在 python 中创建一个 class。

举例说明我想做什么:

foo = Foo()
foo.playlist('my playlist').add('i_add_a_track_in_"my playlist".ogg')
foo.playlist('my playlist').delete('i_remove_this_track.ogg')

我现在有这个代码:

class Foo(object):
    def playlist(self, name):
        pass #my function...
    def add(self, track):
        pass #adding track
    def delete(self, track):
        pass #delete track

请帮帮我,我不知道该怎么做。

谢谢

IIUC,你想一个接一个地链接方法调用吗?您所要做的就是在每个函数的末尾 return self

class Foo(object):
    ...   
    def playlist(self, name):
        ...
        return self

    ... # and so on

MVCE:

In [229]: class Foo:
     ...:     def __init__(self, data):
     ...:         self.data = data
     ...:
     ...:     def add(self, val):
     ...:         self.data += val
     ...:         return self
     ...:
     ...:     def sub(self, val):
     ...:         self.data -= val
     ...:         return self
     ...:     

In [231]: x = Foo(0)

In [232]: x = x.add(10).sub(5) # or just x.add(10).sub(5)

In [233]: x.data
Out[233]: 5

如果我没理解错的话,foo.playlist('someplaylist').do_something()其实应该是

的快捷方式
playlist = foo('someplaylist')
playlist.do_something()

其中 playlist 不是 foo 对象(即:foo.do_something() 没有任何意义,应该只是引发错误),而是一个不同的 class.

如果确实如此,您实际上需要两个 classes:Foo 方法 playlist(...) 那个 returns 一个 Playlist 对象,以及 Playlistadd()delete() 方法:

class Playlist(object):
    def __init__(self, name):
        self.name = name

    def add(self, what):
        print("adding {} to playlist {}".format(what, self.name))

    def delete(self, what):
        print("deleting {} from playlist {}".format(what, self.name))


class Foo(object):
    def playlist(self, name):
        return Playlist(name)