💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
>[success] # 初始化类的init ~~~ 1.使用__new__ 创建一个未初始化的实例,可以理解清空初始化 ~~~ >[danger] ##### 代码案例 ~~~ class Date: def __init__(self, year, month, day): self.year = year self.month = month self.day = day ~~~ * 打印结果 ~~~ 1.通过打印结果发现,这个类已经没有了 init 初始化变量的属性定义 ~~~ ~~~ >>> d = Date.__new__(Date) >>> d <__main__.Date object at 0x1006716d0> >>> d.year Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'Date' object has no attribute 'year' >>> ~~~ * 重新自定义属性 ~~~ >>> data = {'year':2012, 'month':8, 'day':29} >>> for key, value in data.items(): ... setattr(d, key, value) ... >>> d.year 2012 >>> d.month 8 >>> ~~~ >[danger] ##### 升级使用 ~~~ from time import localtime class Date: def __init__(self, year, month, day): self.year = year self.month = month self.day = day @classmethod def today(cls): d = cls.__new__(cls) t = localtime() d.year = t.tm_year d.month = t.tm_mon d.day = t.tm_mday return d ~~~