我想用方法和子方法在python中创建一个类。
示例我要做的事情:
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
请帮助我,我不知道我该怎么做。
谢谢
答案 0 :(得分:2)
IIUC,你想一个接一个地连接方法调用?您需要做的就是在每个函数结束时返回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
答案 1 :(得分:1)
如果我理解正确,foo.playlist('someplaylist').do_something()
实际上应该是
playlist = foo('someplaylist')
playlist.do_something()
其中playlist
不是foo
对象(即:foo.do_something()
不应该有任何意义,应该只是引发错误),而是一个不同类的实例。
如果情况确实如此,那么您实际上需要两个类:Foo
方法playlist(...)
返回Playlist
个对象,Playlist
包含add()
1}}和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)