gpt4 book ai didi

python - 类属性的类型提示

转载 作者:太空宇宙 更新时间:2023-11-04 00:11:42 25 4
gpt4 key购买 nike

我有一个包含许多模型和许多基于类的 View 的 Web 应用程序。大部分代码看起来像这样

from typing import TypeVar, Type

M = TypeVar('M', bound='Model')
TypeModel = Type[M]


# ---------- models
class Model:
@classmethod
def factory(cls: TypeModel) -> M:
return cls()


class ModelOne(Model):
def one(self):
return


class ModelTwo(Model):
def two(self):
return


# ---------- views
class BaseView:
model: TypeModel

@property
def obj(self) -> M:
return self.model.factory()

def logic(self):
raise NotImplementedError


class One(BaseView):
model = ModelOne

def logic(self):
self.obj. # how can i get suggest of methods of ModelOne here?
...


class Two(BaseView):
model = ModelTwo

def logic(self):
self.obj. # how can i get suggest of methods of ModelTwo here?
...

我想要一个属性obj,它是 View 中指定模型的实例。我怎样才能做到这一点?谢谢

最佳答案

您需要使您的 BaseView 类相对于 M 通用。所以,你应该这样做:

from typing import TypeVar, Type, Generic

M = TypeVar('M', bound='Model')

# Models

class Model:
@classmethod
def factory(cls: Type[M]) -> M:
return cls()

class ModelOne(Model):
def one(self):
return

class ModelTwo(Model):
def two(self):
return

# Views

# A BaseView is now a generic type and will use M as a placeholder.
class BaseView(Generic[M]):
model: Type[M]

@property
def obj(self) -> M:
return self.model.factory()

def logic(self):
raise NotImplementedError

# The subclasses now specify what kind of model the BaseView should be
# working against when they subclass it.
class One(BaseView[ModelOne]):
model = ModelOne

def logic(self):
self.obj.one()

class Two(BaseView[ModelTwo]):
model = ModelTwo

def logic(self):
self.obj.two()

请注意:我去掉了你的 TypeModel 类型别名。这部分是文体的,部分是务实的。

在风格上,当我查看类型签名时,我希望能够立即确定它是否使用了泛型/类型变量。使用类型别名往往会掩盖/我真的不喜欢使用上下文相关的类型。

从实用的角度来说,当您过度使用包含类型变量的类型别名时,PyCharm 的类型检查器和 mypy 都会有点挣扎。

关于python - 类属性的类型提示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52345496/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com