稀有对象的 python 类型注释,例如 psycopg2 对象

kuk*_*uza 7 python types annotations python-typing

我了解内置类型。但是我如何指定稀有对象,例如数据库连接对象?

def get_connection_and_cursor() -> tuple[psycopg2.extensions.cursor, psycopg2.extensions.connection]:
    connection = psycopg2.connect(dbname=db_name, user=db_user, password=db_password, host='127.0.0.1', port="5432")
    # connection.autocommit = True
    cursor = connection.cursor()
    return connection, cursor
Run Code Online (Sandbox Code Playgroud)

检查类型,以下是输出:

  • type(cursor)psycopg2.extensions.cursor
  • type(connection)psycopg2.extensions.connection: 。

我应该用它做什么?

rna*_*ath 12

这些是由 定义的自定义类型(类)psycopg2

psycopg2.extensions.cursor代表一个光标,并且

psycopg2.extensions.connection代表一个连接。


即使是内置类型也是底层的类。尝试type(3)一下你就会发现它是一个类型的类int

创建您自己的类,定义变量和方法,如下所示:

class CustomType:
    def __init__(self):   # this is the constructor
        self.x = 3        # this is an instance variable of the class

    def update(self):     # this is an instance method of the class
        self.x += 1       # access instance fields with self param

    @staticmethod         # this is a static method of the class
    def __str__():        # toString equivalent
        return 'abc' 
Run Code Online (Sandbox Code Playgroud)