日期时间模块的日期类的__slots __

时间:2019-03-10 19:22:44

标签: python python-3.x

我做了一些与日期类有关的作品。因此,我在C:\ Python34 \ Lib中读取了datetime.py。顺便说一下,我在使用Python 3.4。我偶然发现这些行代码:

class date:   
    __slots__ = '_year', '_month', '_day'

    def __new__(cls, year, month=None, day=None):        
        if (isinstance(year, bytes) and len(year) == 4 and
            1 <= year[2] <= 12 and month is None):  # Month is sane
            # Pickle support
            self = object.__new__(cls)
            self.__setstate(year)
            return self
        _check_date_fields(year, month, day)
        self = object.__new__(cls)
        self._year = year
        self._month = month
        self._day = day
        return self

......

    @property
    def year(self):
        """year (1-9999)"""
        return self._year

    @property
    def month(self):
       """month (1-12)"""
       return self._month

    @property
    def day(self):
        """day (1-31)"""
        return self._day

我知道__slots__在实例中拒绝创建__dict__。正如我在示例和文档中所读到的,__slots__并不拒绝直接访问Instant / Class属性。但是,对于日期类,我尝试从实例访问_year,_month,_date。它出错了。例如:

In [32]: from datetime import date    
In [33]: mydate = date(2019, 3, 10)
In [34]: mydate._year
>>>AttributeError Traceback (most recent call last) <ipython-input-31-8de5c748f55b> in <module>() ----> 1 mydate._year
AttributeError: 'datetime.date' object has no attribute '_year'

我知道'_'变量表示非直接访问,并且@property年,月,日是其吸气功能。但是,我认为'_'变量即使在声明了__slots__的情况下仍然可以访问

我编写了如下的Foo类进行测试:

class Foo:
    __slots__ = ('_bar',)

    def __new__(cls):    
        self = super().__new__(cls)
        self._bar = 'barz'
        return self

    @property
    def bar(self):
        return self._bar

In [35]: f = Foo()

In [36]: f._bar
Out[36]: 'barz'

此Foo类的实例f尽管使用__slots__和@property

,但访问_bar没有问题。

为什么Foo类可以访问_bar中声明的__slots__而访问_year时却出现日期类错误?

0 个答案:

没有答案