如果您对API不满意,该如何处理?

2024-06-28 10:53:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我在学习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时,这(子类化)是正确的方法吗?你知道吗


Tags: theselfgetpositionbodycurrentwidgetnext
1条回答
网友
1楼 · 发布于 2024-06-28 10:53:13

只要MyListBox仍然能够站在常规ListBox所在的位置,子类化就应该是安全的。毕竟,MyListBox真的是一个ListBox,只是一个特殊的。你知道吗

Urwid documentation本身似乎同意:

Here we are customizing the Filler decoration widget that is holding our Edit widget by subclassing it and defining a new keypress() method. Customizing decoration or container widgets to handle input this way is a common pattern in Urwid applications. This pattern is easier to maintain and extend than handling all special input in an unhandled_input function.

如果你发现自己有太多的空闲时间,你可能还想通读原始Wiki上的Composition Instead Of Inheritance,它可能会给出太多的意见,哪种情况最好。你知道吗

相关问题 更多 >