繁体   English   中英

Python - class 中的 static 方法创建该 ZA2F2ED4F8EBC2CBB1DZC21A29DC40AB6 的实例

[英]Python - static method in class creating instance of that class

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

我有这样的事情:

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"])

我想从PatientJSON创建Patient对象(结构与现有数据库相关,我必须与之集成;它还进行了一些名称属性转换,如您在上面看到的)。 我创建了FromJSONMixin来明确标记可以从 JSON 的相关类创建的类(如PatientJSON )。

问题: -> Patient: part, Unresolved reference 'Patient'出现错误。 为什么? 我不能在同一个 class 的方法中键入 class 对象吗? 我是否必须放弃输入返回类型?

这是创建具有良好类型注释的模块时的常见问题。 问题是当 python 解释器解析用于创建 class 患者的代码时。 方法Patient.from_json的返回类型注解引用了 class Patient 正在解析,尚未创建。 要解决此问题,您通常将 class 名称括在返回注释中并用引号引起来,这样它就变成了一个字符串。 但是现在 MyPy 和其他类型检查器存在问题。 他们不允许字符串返回注释,所以这是一个很好的解决方案:

class MyClass(SomeOtherClass):
    def __init__(self, param_a):
        self.attr_a = param_a
    
    def foo(self, bar: MyClass) -> MyClass:
        return MyClass(self.attr_a + 1)

这将引发未解决的参考错误。

要解决此问题,您可以用引号将方法返回注释括起来

class MyClass(SomeOtherClass):
    def __init__(self, param_a):
        self.attr_a = param_a
    
    def foo(self, bar: 'MyClass') -> 'MyClass':
        return MyClass(self.attr_a + bar.attr_a)

这将适用于可读性,但不适用于 MyPy 等类型检查器。 所以对于像 MyPy 这样的跳棋,你可以创建一个 TypeVar。

from typing import TypeVar, Type

MyClassT = TypeVar('MyClassT', bound='MyClass')

class MyClass(SomeOtherClass):
    def __init__(self, param_a):
        self.attr_a = param_a
    
    def foo(self, bar: Type[MyClassT]) -> MyClassT:
        return MyClass(self.attr_a + bar.attr_a)

暂无
暂无

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

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