欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

类初始化的多种方式

程序员文章站 2022-05-23 18:04:43
...

1.直接__init__

import time


class Date:
    def __init__(self, year, month, day):
        self.year = year
        self.month = month
        self.day = day
Date(2019,4,30)

2.使用类方法实例化

class Date:
    def __init__(self, year, month, day):
        self.year = year
        self.month = month
        self.day = day

    @classmethod
    def today(cls):
        t = time.localtime()

        return cls(t.tm_year, t.tm_mon, t.tm_yday)
d = Date.today()
print(d.year)

3.使用__new__

class Date:
    def __init__(self, year, month, day):
        self.year = year
        self.month = month
        self.day = day
d = Date.__new__(Date)
print(d)
for key, value in data.items(): #设置属性
    setattr(d, key, value)
print(d.year)

4.越过__init__方法实例化

class Date:
   def today2(cls):
        t =time.localtime()
        obj = cls.__new__(cls)
        setattr(obj,'year',t.tm_year)
        setattr(obj,'month',t.tm_mon)
        setattr(obj,"day",t.tm_yday)
        return obj
date = Date.today2()
print(date.year)