gpt4 book ai didi

python - 改变 python 描述符

转载 作者:行者123 更新时间:2023-11-28 16:41:35 28 4
gpt4 key购买 nike

我有这个 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)

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

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

我能做到吗?

谢谢

最佳答案

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

class DateAttribute:
...

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

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

对于 strftime 格式字符串,see the datetime documentation .

像这样工作:

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

关于python - 改变 python 描述符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18770055/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com