Python中文
首页
教程
问答
标签
搜索
登录
注册
python 3.8中的singledispatchmethod和类方法修饰符
回答此问题可获得
20
贡献值,回答如果被采纳可获得
50
分。
<p>我正在尝试使用python 3.8的一个新功能(目前使用的是3.8.3)。在<a href="https://docs.python.org/3/library/functools.html#functools.singledispatchmethod" rel="noreferrer">the documentation</a>之后,我尝试了文档中提供的示例:</p> <pre class="lang-py prettyprint-override"><code>from functools import singledispatchmethod class Negator: @singledispatchmethod @classmethod def neg(cls, arg): raise NotImplementedError("Cannot negate a") @neg.register @classmethod def _(cls, arg: int): return -arg @neg.register @classmethod def _(cls, arg: bool): return not arg Negator.neg(1) </code></pre> <p>但是,这会产生以下错误:</p> <pre><code>... TypeError: Invalid first argument to `register()`: <classmethod object at 0x7fb9d31b2460>. Use either `@register(some_class)` or plain `@register` on an annotated function. </code></pre> <p>如何创建泛型类方法?我的例子中有没有遗漏什么</p> <p><strong>更新:</strong></p> <p>我读过Aashish A的回答,这似乎是一个持续的问题。我已经设法用下面的方法解决了我的问题</p> <pre class="lang-py prettyprint-override"><code>from functools import singledispatchmethod class Negator: @singledispatchmethod @staticmethod def neg(arg): raise NotImplementedError("Cannot negate a") @neg.register def _(arg: int): return -arg @neg.register def _(arg: bool): return not arg print(Negator.neg(False)) print(Negator.neg(-1)) </code></pre> <p>这在版本3.8.1和3.8.3中似乎有效,但似乎不应该,因为我在两个undescore函数上都没有使用staticmethod decorator。这确实适用于类方法,即使问题似乎表明了相反的情况</p> <p>请记住,如果您使用的是IDE,linter不会对这种方法感到满意,会抛出很多错误</p>
0 条评论
分类:
Python问答
请先
登录
后评论
默认排序
时间排序
1 个回答
匿名
1天前
擅长:python、mysql、java
<p>这似乎是<a href="https://bugs.python.org/issue39679" rel="noreferrer">this issue</a>中记录的functools库中的一个bug</p>
请先
登录
后评论
针对此问题:
更多的回答
关注
89
关注
收藏
1
收藏,
216
浏览
网友 提问于 2天前
相关Python问题
无法使用Django/mongoengine连接到MongoDB(身份验证失败)
5 回答
无法使用Django\u mssql\u后端迁移到外部hos
1 回答
无法使用Django&Python3.4连接到MySql
1 回答
无法使用Django+nginx上载媒体文件
8 回答
无法使用Django1.6导入名称模式
4 回答
无法使用Django1.7和mongodb登录管理站点
10 回答
无法使用Djangoadmin创建项目,进程使用了错误的路径,因为我事先安装了错误的Python
5 回答
无法使用Djangockedi验证CBV中的字段
7 回答
无法使用Djangocketditor上载图像(错误400)
3 回答
无法使用Djangocron进行函数调用
7 回答
无法使用Djangofiler djang上载文件
9 回答
无法使用Djangokronos
3 回答
无法使用Djangomssql provid
5 回答
无法使用Djangomssql连接到带有Django 1.11的MS SQL Server 2016
6 回答
无法使用Djangomssq迁移Django数据库
2 回答
无法使用Djangonox创建用户
1 回答
无法使用Djangopyodb从Django查询SQL Server
10 回答
无法使用Djangopython3ldap连接到ldap
9 回答
无法使用Djangoredis连接到redis
1 回答
无法使用Django中的FK创建新表
7 回答