开发者社区> 问答> 正文

类型提示__call __()magic method

我使用一个简单但功能强大的类,它充当数据库表,内置过滤器方法。这是它的一小部分。

PyCharm没有显示#3的类型提示。

from dataclasses import dataclass

@dataclass
class Record:

ID: int

class Table(list):

"""Like a database table.

Usage:
table = Table([Record(123), ...])
>> table.filter(123)
Record(123)
"""
def __call__(self, ID) -> Record:
    return self.filter(ID)

def filter(self, ID) -> Record:
    return Table(x for x in self if x.ID == ID)[0]

table = Table([Record(123)])

table[0]. # 1. This works. ".ID" Pops up after typing the period.
table.filter(123). # 2. This works too.
table(123). # 3. Crickets :-(. Nothing pops up after typing the period.
我做错了什么或者这是PyCharm中的错误?

展开
收起
一码平川MACHEL 2019-01-22 11:33:11 1647 0
1 条回答
写回答
取消 提交回答
  • 问题似乎是Table子类list。如果我们实现所需的容器方法Table而不是子类化,list那么自动完成按预期工作,例如:

    from dataclasses import dataclass

    @dataclass
    class Record:

    ID: int
    

    class Table:

    def __init__(self, items):
        ...
    
    def __getitem__(self, ID) -> Record:
        ...
    
    def __call__(self, ID) -> Record:
        return self.filter(ID)
    
    def filter(self, ID) -> Record:
        return Table(x for x in self if x.ID == ID)[0]
    

    table = Table([Record(123)])
    table[0]. # works
    table.filter(123). # works
    table(123). # works
    我在PyCharm Professional 2018.3.2上测试过。

    2019-07-17 23:26:12
    赞同 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
OPEN SOURCE IN A DATA-DRIVEN WORLD 立即下载
低代码开发师(初级)实战教程 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载