我做了一些与日期类有关的作品。因此,我在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
为什么Foo类可以访问_bar
中声明的__slots__
而访问_year
时却出现日期类错误?