简体   繁体   English

键入提示列表的子类

[英]Type hint a subclass of list

I use a class which subclasses the built-in list. 我使用一个子类内置列表的类。

class Qry(list):
    """Stores a list indexable by attributes."""

    def filter(self, **kwargs):
        """Returns the items in Qry that has matching attributes.

        Example:
            obj.filter(portfolio='123', account='ABC').
        """

        values = tuple(kwargs.values())

        def is_match(item):
            if tuple(getattr(item, y) for y in kwargs.keys()) == values:
                return True
            else:
                return False

        result = Qry([x for x in self if is_match(x)], keys=self._keys)

        return result

Now I want to type hint: 现在我要输入提示:

class C:
    a = 1

def foo(qry: Qry[C]):
    """Do stuff here."""

How do you type hint a custom container class in python 3.5+? 如何在python 3.5+中键入提示自定义容器类?

You can do this rather easily: 你可以很容易地做到这一点:

from typing import TypeVar, List
T = TypeVar('T')
class MyList(List[T]): # note the upper case
    pass

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM