编辑Python的内置日期时间模块(只是为了测试内置模块的编辑如何工作)。但它仍然表现得好像从未改变过

问题描述 投票:0回答:1

在 Ubuntu 和 Windows 上都尝试过此操作

Python 3.8.10 (tags/v3.8.10:3d8993a, May  3 2021, 11:34:34) [MSC v.1928 32 bit (
Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import datetime
>>> datetime.__file__
'C:\\Program Files\\python3810\\lib\\datetime.py'

然后编辑文件。只是为了测试替换了

isoformat
class date

方法的返回行
class date:
...
    def isoformat(self):
        """Return the date formatted according to ISO.

        This is 'YYYY-MM-DD'.

        References:
        - http://www.w3.org/TR/NOTE-datetime
        - http://www.cl.cam.ac.uk/~mgk25/iso-time.html
        """
        # return "%04d-%02d-%02d" % (self._year, self._month, self._day)
        return "%04d-%02d" % (self._year, self._month)

    __str__ = isoformat

重新加载Python shell,但是str的返回是一样的。

Python 3.8.10 (tags/v3.8.10:3d8993a, May  3 2021, 11:34:34) [MSC v.1928 32 bit (
Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import datetime
>>> d = datetime.date.today()
>>> d
datetime.date(2023, 11, 16)
>>> d.__str__()
'2023-11-16'

那么,这是否应该像这样工作,还是必须做其他事情?

python python-3.x python-packaging
1个回答
0
投票

你走错了路。 尝试使用来自 datetime 模块对象的继承,尽管这并不完全是微不足道的。

import datetime

class MyDate(datetime.date):
    def __new__(cls, *args, **kwargs):
        return super().__new__(cls, *args, **kwargs)
    def isoformat(self):
        return "%04d-%02d" % (self.year, self.month)
    __str__ = isoformat

if __name__ == '__main__':
    date = MyDate(1,2,3)
    print(date)
© www.soinside.com 2019 - 2024. All rights reserved.