2014-01-17 80 views
2

我有我自己的DateTime這是從datetime.datetime一個子類:屬性添加到datetime.datetime

class DateTime(datetime.datetime): 
    def __new__(cls, **kwargs): 
     cls.my_attr = kwargs.pop('my_attr') 
     return datetime.datetime.__new__(cls, **kwargs) 

當我創建一個或多個實例每個instance.my_attr指向同一個對象,它是cls.my_attr

>>> dt1 = DateTime(**{'year': 2014, 'month': 1, 'day': 17, 'hour': 18, 'minute': 10, 'my_attr': 'dt1'}) 
>>> dt1.my_attr 
'dt1' 
>>> dt2 = DateTime(**{'year': 2015, 'month': 2, 'day': 18, 'hour': 19, 'minute': 11, 'my_attr': 'dt2'}) 
>>> dt1.my_attr 
'dt2' 
>>> dt2.my_attr 
'dt2' 
>>> id(dt1.my_attr) 
23429768 
>>> id(dt2.my_attr) 
23429768 
>>> id(DateTime.my_attr) 
23429768 

怎麼了?

回答

3

你正在改變類的屬性而不是實例。你應該先創建實例,然後分配給ATTRIB它:

class DateTime(datetime.datetime): 
    def __new__(cls, **kwargs): 
     my_attr = kwargs.pop('my_attr') 
     dt = datetime.datetime.__new__(cls, **kwargs) 
     dt.my_attr = my_attr 
     return dt 

測試:

>>> dt1 = DateTime(**{'year': 2014, 'month': 1, 'day': 17, 'hour': 18, 'minute': 10, 'my_attr': 'dt1'}) 
>>> dt2 = DateTime(**{'year': 2015, 'month': 2, 'day': 18, 'hour': 19, 'minute': 11, 'my_attr': 'dt2'}) 
>>> dt1.my_attr 
'dt1' 
>>> dt2.my_attr 
'dt2' 
+0

非常感謝...! – mutetella