【问题标题】:Alter python descriptor改变python描述符
【发布时间】:2013-09-12 16:50:26
【问题描述】:

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

我能做到吗?

谢谢

【问题讨论】:

  • 仅当描述符返回具有format1format2 等属性(或属性)的对象时。 IE。 x.thisdate不会返回字符串
  • (不使用描述符的建议更好。)
  • 另外,如果您的描述符是您的实际用例,您可以只使用 Enthought Traits。
  • 除非您有明确的理由使用描述符,否则只需使用属性:x.thisdate = datetime.date(…)。正如您所拥有的那样,您已经创建了一个绝对不执行任何操作的类 DateAttribute。使用描述符的一个不好的原因是“因为我必须在 Java/C++ 中这样做,而且我不明白为什么 Python 没有私有实例变量。”

标签: python descriptor


【解决方案1】:

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

【讨论】:

  • 如果我使用你的代码:x.thisdate.format 我收到 AttributeError: 'datetime.date' object has no attribute 'format1'
  • 那我该如何选择呢?
  • 好的。在您的示例中,您在初始化描述符时使用属性。但我想在 D 类的实例中使用它们?
  • 我运行您的代码广告接收:initing <__main__.DateAttribute instance at 0x7f116737c0e0> 2013-01-01 Traceback (most recent call last): File "aaa.py", line 32, in <module> print (d.thisdate.format1) AttributeError: 'datetime.date' object has no attribute 'format1'
  • 确切的代码(第二个 sn-p)在我的机器上使用 Python 3.2.4 (default, May 10 2013, 08:57:38) [GCC 4.7.3] on linux2 按预期运行。
猜你喜欢
  • 2012-11-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多