相关疑难解决方法(0)

Python:对于继承的类,类型提示返回类实例的类方法

考虑以下:

from __future__ import annotations

class A:

    def __init__(self):
        print("A")
        self.hello = "hello"

    # how do I type this so that the return type is A for A.bobo()
    # and B for B.bobo()?
    @classmethod
    def bobo(cls) -> UnknownType:
        return cls()


class B(A):

    def __init__(self):
        print("B")
        super().__init__()
        self.world = "world"


instance_of_B = B.bobo()  # prints "B", then "A", and returns an instance of B
Run Code Online (Sandbox Code Playgroud)

我想对类方法进行类型提示,以便 mypy 可以知道,在s方法bobo的情况下,它不仅仅是返回的实例,而且实际上是 的实例。我真的不清楚如何做到这一点,或者是否可能。我认为类似的东西可能会起作用,但我不确定这对 mypy 是否具有语法意义。BboboABType[cls]

python typing mypy

11
推荐指数
2
解决办法
8938
查看次数

返回基类的子类实例的工厂方法的Python 3类型提示

假设我有两个类,Base并且在中Child有一个工厂方法Base。factory方法调用另一个类方法,该类方法可以被Base的子类覆盖。

class Base(object):
    @classmethod
    def create(cls, *args: Tuple) -> 'Base':
        value = cls._prepare(*args)
        return cls(value)

    @classmethod
    def _prepare(cls, *args: Tuple) -> Any:
        return args[0] if args else None

    def __init__(self, value: Any) -> None:
        self.value = value


class Child(Base):
    @classmethod
    def _prepare(cls, *args: Tuple) -> Any:
        return args[1] if len(args) > 1 else None

    def method_not_present_on_base(self) -> None:
        pass
Run Code Online (Sandbox Code Playgroud)

有没有一种注释的方法,Base.create以便静态类型检查器可以推断Base.create()返回的实例BaseChild.create()返回的实例Child,以便下面的示例通过静态分析?

base = …
Run Code Online (Sandbox Code Playgroud)

python type-hinting python-3.x

9
推荐指数
2
解决办法
2118
查看次数

Python - 类中的静态方法创建该类的实例

我有从 JSON 创建的 Python 数据类(实际上有很多)。我想要一种从 JSON 创建类实例的方法。

我有这样的事情:

class FromJSONMixin:
    @staticmethod
    @abstractmethod
    def from_json(json: Union[Dict, TypedDict], **kwargs):
        raise NotImplementedError


class PatientJSON(TypedDict):
    ID: str
    Name: str
    Description: str
    BirthDate: str


@dataclass
class Patient(FromJSONMixin):
    name: str
    birth_date: str
    description: str

    @staticmethod
    def from_json(json: PatientJSON, **kwargs) -> Patient:
        return Patient(
        name=json["Name"],
        birth_date=json["BirthDate"],
        description=raw_data["Description"])
Run Code Online (Sandbox Code Playgroud)

我想Patient从中创建对象PatientJSON(结构与现有数据库相关,我必须与它集成;它还进行一些名称属性翻译,如上所示)。我创建了FromJSONMixin来显式标记可以从 JSON 的相关类创建的类(例如PatientJSON)。

问题:-> Patient:我收到零件错误Unresolved reference 'Patient'。为什么?我无法在同一类的方法中键入类对象?我是否必须放弃输入返回类型?

python json static-methods dictionary python-typing

6
推荐指数
1
解决办法
2664
查看次数

mypy:如何在泛型类中声明返回 self 的方法的返回类型?

这个答案似乎不适用于泛型。在检查以下代码时,Mypy 抱怨“错误:缺少泛型类型 A 的类型参数”。我尝试使用'A[T]'TypeVar 但 mypy 说“错误:类型变量 T 未绑定。” 我还尝试使用AnyA[T]作为返回类型,get但会产生两个错误消息,即已知的“错误:缺少泛型类型 A 的类型参数”和新的错误消息“与参数一起使用的类型变量 AnyA”。

如何正确指定返回类型get

import typing

T = typing.TypeVar('T')
AnyA = typing.TypeVar('AnyA', bound='A')

class A(typing.Generic[T]):

    def __init__(self, val: T) -> None:
        self.val = val

    def get(self: AnyA) -> AnyA:
        return self

class B(A[T]):
    def is_int(self) -> bool:
        return isinstance(self.val, int)


if __name__ == '__main__':
    b = B(42)
    print(b.get().is_int())
Run Code Online (Sandbox Code Playgroud)

generics mypy python-typing

5
推荐指数
1
解决办法
2899
查看次数