4

我有这个 python 描述符:

# Date Descriptor
class DateAttribute():
    def __init__(self, value=None):
        self.value = value
    def __get__(self, instance, value):
        return self.value
    def __set__(self, instance, value):
        if type(value) is not datetime.date: 
            raise TypeError('A date value is expected')
        self.value = value

和使用此描述符的 D 类:

class D:
    thisdate = DateAttribute()

我将此类用作:

x = D()
x.thisdate = datetime.date(2012, 9, 12)

我希望扩展描述符以在某些方面给我格式化的结果。埃斯。

x.thisdate.format1
>>> '2012 9 12'
x.thisdate.format2
>>> '2012___9___12'
x.thisdate.format3
>>> '2012####9####12'
.....

我能做到吗?

谢谢

4

1 回答 1

4

formatX属性添加到您的类并相应地格式化:

class DateAttribute:
    ...

    @property
    def format1 (self): return self.value.strftime (SOMEFORMAT)

    @property
    def format2 (self): return self.value.strftime (SOMEOTHERFORMAT)

对于 strftime 格式字符串,请参阅 datetime 文档

像这样工作:

thisdate = DateAttribute (datetime.date (2012, 9, 12) )
print (thisdate.format1)

编辑:

#! /usr/bin/python3

import datetime

class DateAttribute:
    def __init__(self, value=None):
        print ('initing')
        self.value = value

    def __get__(self, instance, value):
        print ('getting')
        if not self.value: return self.value
        return FormattedDate (self.value.year, self.value.month, self.value.day)

    def __set__(self, instance, value):
        print ('setting')
        if not isinstance (value, datetime.date): raise TypeError('A date value is expected')
        self.value = value


class FormattedDate (datetime.date):
    @property
    def format1 (self): return self.strftime ('%Y==%m==%d')

class D:
    thisdate = DateAttribute ()

d = D ()
print (d.thisdate)
d.thisdate = datetime.date (2013, 1, 1)
print (d.thisdate)
print (d.thisdate.format1)

产生这个输出:

initing
getting
None
setting
getting
2013-01-01
getting
2013==01==01
于 2013-09-12T16:57:03.827 回答