簡體   English   中英

如何設置 class 方法從 class 屬性返回動態輸入

[英]How to set a class method return typing dynamically from a class property

我在我的一個寵物項目中工作,發現了這個小問題。 我想在基數 class 中使用類型,問題是 class 方法的返回類型由子類設置的字段定義。 這是我的基地 class

class BaseRepository(metaclass=RequiredAttributes('model')):

    model = None  # The subclasses have to define the this field with a class type.
                  # All the class methods will return objects of the same
                  # type as this field.

    def get(self, id) -> ??:
        # return an object of the type defined in mode
        ...


class UserRepo(BaseRepository): # subclass

    model = User # class type

    ...


我想將get function 的類型設置為與 model 字段中定義的 object 類型相同。

關於如何完成這樣的事情有什么建議嗎?

如果沒有元類,這將傳遞 MyPy ,它能夠正確地推斷出xUser類型。 我無法使用元類對其進行測試,因為我沒有您的元類定義。 該解決方案使用參數化的Generic作為基礎 class,這允許您向類型檢查器斷言 class 中的不同方法將具有相同的參數和返回參數類型。 Django 的存根文件中使用了類似的技術。

注意如果您使用的是 Python <= 3.8,則您必須從typing模塊導入Type並使用Optional[Type[M]]而不是Optional[type[M]]作為model注釋。

from typing import Optional, Generic, TypeVar


M = TypeVar('M')


class BaseRepository(Generic[M], metaclass=RequiredAttributes('model')):
    model: Optional[type[M]] = None     # The subclasses have to define the this field with a class type.
                                        # All the class methods will return objects of the same
                                        # type as this field.

    def get(self, id: int) -> M: ...
        # return an object of the type defined in mode
        

class User:
    pass


class UserRepo(BaseRepository[User]): # subclass
    model = User # class type
    

x = UserRepo().get(1)
reveal_type(x)  # Revealed type is "__main__.User*"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM