gpt4 book ai didi

python 类只读属性(在日期时间)

转载 作者:太空狗 更新时间:2023-10-30 02:25:39 26 4
gpt4 key购买 nike

我知道将属性设置为私有(private)的一种快速方法是在属性之前使用 __ (稍后更正,因为这实际上是为了名称修改,而不是为了限制访问), 或者使用@property

但是,我发现对于 python 标准库模块,例如 datetime ,这是设置了不同的方式?

要解释我的问题,请转至the source code of datetime

我们以 timedelta 类为例:

class timedelta:
...
...
...

timedelta.min = timedelta(-999999999)
timedelta.max = timedelta(days=999999999, hours=23, minutes=59, seconds=59,
microseconds=999999)
timedelta.resolution = timedelta(microseconds=1)

类属性是在类外设置的?为什么?

如果我:

import datetime
d= datetime.timedelta(days=1, hours=12)
print(d)
print(d.max) # >>> 999999999 days, 23:59:59.999999
print(type(d.max)) # >>> <class 'datetime.timedelta'>

d.max = 1000 # regardless of the reason, if I just want to do this
# >>> AttributeError: 'datetime.timedelta' object attribute 'max' is read-only

我想知道这个AttributeError 是从哪里来的?我在源代码的任何地方都找不到会引发此​​错误消息的地方?

谢谢!

最佳答案

The class attributes was set outside of the class? why?

timedelta 在执行 timedelta 类的主体时不存在。在创建类对象并可以单独使用之前,您必须执行 class timedelta: block 中的所有代码。

I wonder where does this AttributeError coming from? I can not find in anywhere in the source code that this error message will be raised?

datetime 模块是用纯 Python 编写的,但是 tries to use更快的模块 written in C如果可以的话。纯 Python 代码按您的预期工作:

>>> import sys
>>> sys.modules['_datetime'] = None # prevent the C module from loading
>>> from datetime import timedelta
>>> timedelta.min = 5
>>> timedelta.min
5

timedelta 类有 tp_flags设置为 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE .您只能设置包含 Py_TPFLAGS_HEAPTYPE flag 的对象的属性.

关于python 类只读属性(在日期时间),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48432316/

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