Python 如何为 class 添加 Typing hint?

Python 如何为 class 添加 Typing hint?

先上代码:

from typing import TypeVar, Generic

from abc import abstractclassmethod

from typing import Any

class BaseConnection:

@abstractmethod

def connect(self):

pass

class MysqlConnection(BaseConnection):

def connect(self):

pass

class PGsqlConnection(BaseConnection):

def connect(self):

pass

class SqlLiteConnection(BaseConnection):

def connect(self):

pass

def create_connnection(conn_constructor: Any) -> Any:

return conn_constructor()

if __name__ == '__main__':

connection = create_connnection(conn=SqlLiteConnection)

有这么一个需求,我有一个 create_connnection 函数,其中的 conn_constructor 可以是 SqlLiteConnection、PGsqlConnection、MysqlConnection 等等任意一个

我改为 conn_constructor 参数添加什么 typing hints 可以实现,参数是什么 class ,返回值就是什么 class 的实例?

显然,Any 不是什么好东西,因为失去了 IDE 的代码补全


我本来想用泛型:

python">from typing import TypeVar, Generic

from abc import abstractclassmethod

from typing import Any

ConnConstructor = TypeVar('ConnConstructor')

class BaseConnection:

@abstractmethod

def connect(self):

pass

class MysqlConnection(BaseConnection):

def connect(self):

pass

class PGsqlConnection(BaseConnection):

def connect(self):

pass

class SqlLiteConnection(BaseConnection):

def connect(self):

pass

def create_connnection(conn_constructor: ConnConstructor) -> ConnConstructor:

return conn_constructor()

if __name__ == '__main__':

connection = create_connnection(conn_constructor=SqlLiteConnection)

connection.connect()

但是有一个问题,就是 conn_constructor 参数的类型是 type ,而不是 class,但是写 type 就奇奇怪怪!

conn_constructor: ConnConstructor conn_constructor 不是类实例,而是类,写 typing 好像要写 conn_constructor: type 是吗?


回答:

找到解决办法了:

from typing import TypeVar, Generic

from abc import abstractclassmethod

from typing import Type

ConnConstructor = TypeVar('ConnConstructor')

class BaseConnection:

@abstractmethod

def connect(self):

pass

class MysqlConnection(BaseConnection):

def connect(self):

pass

class PGsqlConnection(BaseConnection):

def connect(self):

pass

class SqlLiteConnection(BaseConnection):

def connect(self):

pass

def create_connnection(conn_constructor: Type[ConnConstructor]) -> ConnConstructor:

return conn_constructor()

if __name__ == '__main__':

connection = create_connnection(conn_constructor=SqlLiteConnection)

connection.connect()

使用 conn_constructor: Type[ConnConstructor]

conn_constructor 的 typing hint 不是 ConnConstructor,而是 type,但是只写 type 就太 typing less 的,所以,我们可以用中括号 Type[ConnConstructor]

这样就不会单独 IDE 的自动补全了!

以上是 Python 如何为 class 添加 Typing hint? 的全部内容, 来源链接: utcz.com/p/938524.html

回到顶部