[英]Python - How to dynamically get the class instance and return type
目前,我在 Python 下面繼承了 class 結構並創建了小工廠 class 來獲取子實例 class 如下。
在這里我想要建議
PersonFacotry
class 的create
方法中,截至目前,我將返回類型設置為Any
,是否可以動態返回類型為Engineer
或Doctor
?from typing import Any
class Person: pass
class Engineer(Person): pass
class Doctor(Person): pass
class PersonFactory:
class_mapper = {'engineer': Engineer, 'doctor': Doctor}
@classmethod
def create(cls, type: str) -> Any:
return cls.class_mapper[type]
doctor_instance = PersonFactory().create('doctor')()
engineer_instance = PersonFactory().create('engineer')()
非常感謝!
在我看來,這實際上是一個很好的方法。 事實上,它的可讀性很強,也很容易理解!
是的,您可以將Any
替換為Person
:
class PersonFactory:
def create(cls, type: str) -> Person:
return class_mapper[type]
回顧一下:
代碼 1:
from typing import Any
class Person:pass
class Engineer(Person):pass
class Doctor(Person):pass
doctor_instance = Doctor()
engineer_instance = Engineer()
print(doctor_instance,type(doctor_instance), type(doctor_instance).__bases__)
print(engineer_instance, type(engineer_instance), type(engineer_instance).__bases__)
output:
<__main__.Doctor object at 0x7f28eedeb4c0> <class '__main__.Doctor'> (<class '__main__.Person'>,)
<__main__.Engineer object at 0x7f28eecf6d90> <class '__main__.Engineer'> (<class '__main__.Person'>,)
代碼 2:
from typing import Any
class Person:pass
class Engineer(Person):pass
class Doctor(Person):pass
class PersonFactory:
class_mapper = {'engineer': Engineer,'doctor': Doctor}
@classmethod
def create(cls, tipo: str) -> Any:
return cls.class_mapper[tipo]()
doctor_instance = PersonFactory().create('doctor')
engineer_instance = PersonFactory().create('engineer')
print(doctor_instance, type(doctor_instance), type(doctor_instance).__bases__)
print(engineer_instance, type(engineer_instance), type(engineer_instance).__bases__)
output:
<__main__.Doctor object at 0x7fe7ac5647f0> <class '__main__.Doctor'> (<class '__main__.Person'>,)
<__main__.Engineer object at 0x7fe7ac564550> <class '__main__.Engineer'> (<class '__main__.Person'>,)
代碼 2 應該用於
如何動態獲取class實例
有關
返回類型
def create(cls, tipo: str) -> class_mapper[tipo]:
引發NameError: name 'tipo' is not defined
mypy code2.py
給出:
error: Variable "code2.PersonFactory.class_mapper" is not valid as a type
不是Python的專家,注釋更少,我在SO上找到了這個:
是否可以在Python的function注解中引用function參數?
我不確定是否相關但聲明:
注釋必須是有效的表達式,在定義 function 時不會引發異常(但請參閱下面的前向引用)。
注釋應保持簡單,否則 static 分析工具可能無法解釋這些值。 例如,動態計算的類型不太可能被理解。 (這是一個有意模糊的要求,具體的包含和排除可能會根據討論的保證添加到本 PEP 的未來版本中。)
我會說你的方法很有趣,可能對 static 分析有用。 但是如果我們接受 PEP 作為當前注釋范例的解釋來源,突出顯示的文本解釋了為什么在調用 function 時不能動態定義返回類型。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.