我在学习urwid。你知道吗
Urwid列表框有一个不适合我的API。例如,为了将焦点切换到下一个/上一个元素,我想写:
listbox.focus_next() / listbox.focus_previous()
但是urwid.ListBox文件是这样的:
1)关注列表框中的前一个元素
listwalker = listbox.body
widget,current_position = listwalker.get_focus()
try :
widget,previous_position = listwalker.get_prev(current_position)
listwalker.set_focus(previous_position)
except :
# you're at the beginning of the listbox
pass
2)关注列表框中的下一个元素
# same code, except that you change get_prev with get_next
listwalker = listbox.body
widget,current_position = listwalker.get_focus()
try :
widget,next_position = listwalker.get_next(current_position)
listwalker.set_focus(next_position)
except :
# you're at the end of the listbox
pass
请注意,所有这些方法都不是在listbox本身上调用的,而是在它的一个属性(body)上调用的。你知道吗
不满意这种情况,我决定将listbox本身子类化,为API提供两个新服务(方法):focus\u previous()和focus\u next(),如下所示:
class MyListBox(urwid.ListBox):
def focus_next(self):
try:
self.body.set_focus(self.body.get_next(self.body.get_focus()[1])[1])
except:
pass
def focus_previous(self):
try:
self.body.set_focus(self.body.get_prev(self.body.get_focus()[1])[1])
except:
pass
在处理不愉快的api时,这(子类化)是正确的方法吗?你知道吗
只要
MyListBox
仍然能够站在常规ListBox
所在的位置,子类化就应该是安全的。毕竟,MyListBox
真的是一个ListBox
,只是一个特殊的。你知道吗Urwid documentation本身似乎同意:
如果你发现自己有太多的空闲时间,你可能还想通读原始Wiki上的Composition Instead Of Inheritance,它可能会给出太多的意见,哪种情况最好。你知道吗
相关问题 更多 >
编程相关推荐