gpt4 book ai didi

python - 如果您对 API 不满意该怎么办?

转载 作者:太空宇宙 更新时间:2023-11-03 18:46:13 25 4
gpt4 key购买 nike

我正在学习 urwid。

Urwid 列表框有一个不适合我的 API。例如,为了将焦点更改为下一个/上一个元素,我想写:

listbox.focus_next() / listbox.focus_previous()

但是urwid.ListBox提供的API是这样的:

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

请注意,所有这些方法都不是在列表框本身上调用的,而是在其属性之一(主体)上调用的。

对这种情况不满意,我决定对列表框本身进行子类化,为 API 提供两个新服务(方法):focus_previous() 和 focus_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其本身似乎也同意:

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.

如果您发现自己有太多空闲时间,您可能还想阅读Composition Instead Of Inheritance在原始 Wiki 上,它可能给出了太多关于哪种情况最好的意见。

关于python - 如果您对 API 不满意该怎么办?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19465847/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com