构造函数与析构函数,单例类,attr方法
2026/8/11 5:08:22 网站建设 项目流程

构造函数

构造函数是类中在创建对象时自动调用的特殊方法,用于初始化对象的属性

class Person: def __new__(cls, *args, **kwargs): """用于创建实例并且返回实例""" instance = object.__new__(cls) return instance

析构函数

析构函数是对象被销毁时自动调用的特殊方法,用于清理资源

def __del__(self): """析构函数:对象销毁时自动调用""" print(f"{self} 被销毁了") # 清理资源

单例类

单例模式确保一个类只有一个实例,并提供全局访问点。

class BaseManage: instance = None def __new__(cls, *args, **kwargs): if cls.instance is None: obj = super().__new__(cls) cls.instance = obj return cls.instance class PersonManage(BaseManage): def __init__(self): self.person_list = [] pm1 = PersonManage() pm2 = PersonManage() print(pm1 is pm2)

attr 方法

hasattr(obj, name)检查是否有某属性True/False
getattr(obj, name, default)获取属性值属性值
setattr(obj, name, value)设置属性值None
delattr(obj, name)删除属性None

attr方法的单例类

class PersonManage: def __new__(cls, *args, **kwargs): if not hasattr(cls, "instance"): obj = super().__new__(cls) setattr(cls, "instance", obj) return getattr(cls, "instance") pm1 = PersonManage() pm2 = PersonManage() print(pm1 is pm2)

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询