我了解内置类型。但是如何指定稀有对象,例如数据库连接对象?
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
检查类型,这是的输出
type(cursor)
:psycopg2.extensions.cursor
和type(connection)
:psycopg2.extensions.connection
我该怎么处理它?
这些是psycopg2
定义的自定义类型(类(。
psycopg2.extensions.cursor
表示光标,
CCD_ 7表示连接。
即使是内置类型也是隐藏的类。试试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'