Python中文
首页
教程
问答
标签
搜索
登录
注册
Python使用Python的方式functools.singledispatch在课堂上?
回答此问题可获得
20
贡献值,回答如果被采纳可获得
50
分。
<p>我正在过渡到Python3,并一直在探索stdlib的一些功能。<a href="http://www.python.org/dev/peps/pep-0443/" rel="nofollow">functools.singledispatch</a>引起了我的注意,我一直在玩它。然而,在我尝试在课堂上使用它的时候,我遇到了一些问题。在</p> <p>它似乎不适用于类内注册的函数,您可以通过直接调用乐趣。快感(type(arg))(argname=arg),我想知道是否有更好的方法来实现它。在</p> <p>我尝试在注册的上面和下面使用@classmethod和@staticmethod作为装饰器,但是没用。在</p> <p>下面是一个人为的例子,它注册处理程序,以便在创建类时转换输入参数,以确保它始终是一个列表。在</p> <pre><code>from functools import singledispatch class UrlDispatcher(object): @singledispatch def url_input(self, input): print('input wasn\'t dispatched', input) @url_input.register(str) def _(self, input): print('input is a str', input) self.input = [input] @url_input.register(list) def _(self, input): print('input is a list', input) self.input = input def __init__(self, arg): # Works, albeit clunkily self.url_input.dispatch(type(arg))(self,input=arg) # Always uses the base dispatcher self.url_input(input=arg) a = "http://www.cnn.com" b = ["http://www.google.com", "http://www.slashdot.org"] s1 = UrlDispatcher(a) s2 = UrlDispatcher(b) </code></pre>
0 条评论
分类:
Python问答
请先
登录
后评论
默认排序
时间排序
1 个回答
匿名
1天前
擅长:python、mysql、java
<p>下面的方法应该行得通。不管这是不是最好的解决办法,我不知道。在</p> <pre><code>class Foo: def method(self, arg): _method(arg, self) @functools.singledispatch def _method(arg, self): ... ... ... </code></pre>
请先
登录
后评论
针对此问题:
更多的回答
关注
89
关注
收藏
1
收藏,
216
浏览
网友 提问于 2天前
相关Python问题
文本导入时标题行中的特殊字符
3 回答
文本小部件:在没有输入时更新并在循环后保持空闲
5 回答
文本小部件tkin
5 回答
文本小部件tkinter中的标签更改或文本外观更改是否有撤消功能?
6 回答
文本小部件tkinter复制图像选项
10 回答
文本小部件上的Python Tkinter ttk滚动条未缩放
5 回答
文本小部件上的滚动条可能需要根据制表符ord显示前进行滚动
6 回答
文本小部件不显示lis中的内容
10 回答
文本小部件不显示Unicode字符
2 回答
文本小部件中写入的行间距
6 回答
文本小部件中的文本作为变量
8 回答
文本小部件中的滚动条仅显示在底部
1 回答
文本小部件中的选项卡键空间计数
3 回答
文本小部件作为Lis
7 回答
文本小部件在主框架中扩展列宽
8 回答
文本小部件未使用删除功能清除
7 回答
文本小部件滚动动画(Tkinter、Python)
9 回答
文本居中。格式正确吗?
9 回答
文本差分算法
5 回答
文本已知时音频文件中的单词索引
7 回答