Python 的 元类

等级 5349 次按键

这使用元类实现单例模式,确保类只存在一个实例。

Python 代码

# 定义继承自type的元类
1class SingletonMeta(type):
# 类级字典,把每个类映射到它唯一的实例
2 _instances = {}
3
# __call__在调用Database()时运行,早于__init__
4 def __call__(cls, *args, **kwargs):
# 检查实例是否已存在
5 if cls not in cls._instances:
# 仅在不存在时创建新实例
6 cls._instances[cls] = super().__call__(*args, **kwargs)
# 返回现有或新实例
7 return cls._instances[cls]
8
# 使用单例元类定义类
9class Database(metaclass=SingletonMeta):
# 初始化数据库连接
10 def __init__(self):
# 标记为已连接
11 self.connected = True
12
# 创建第一个实例
13db1 = Database()
# 第二次调用:返回同一个对象
14db2 = Database()
# 验证两个变量指向同一个实例
15print(f"Same instance: {db1 is db2}")

运行结果

Same instance: True
用这段代码练习打字

可以用这段代码练习打字。成绩不会计入排行榜。

这段代码中的符号

这段 Python 代码中需要输入的符号及其出现次数。

  • _× 16
  • (× 9
  • )× 9
  • :× 6
  • *× 6
  • =× 6
  • .× 5
  • ,× 3
  • "× 2
  • [× 2

Python 等级 5 的更多代码示例

← 返回 Python 打字练习