为什么我不能直接将属性添加到任何Python对象? [英] Why can't I directly add attributes to any python object?

查看:159
本文介绍了为什么我不能直接将属性添加到任何Python对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的code:

>>> class G:
...   def __init__(self):
...     self.x = 20
...
>>> gg = G()
>>> gg.x
20
>>> gg.y = 2000

这code:

>>> from datetime import datetime
>>> my_obj = datetime.now()
>>> my_obj.interesting = 1
*** AttributeError: 'datetime.datetime' object has no attribute 'interesting'

这是我的Python知识,我要说的是,日期时间覆盖 SETATTR / GETATTR ,但我不知道。你可以在这里提供一些线索?

From my Python knowledge, I would say that datetime overrides setattr/getattr, but I am not sure. Could you shed some light here?

编辑:我不是在日期时间特别感兴趣。我想知道对一般的对象。

I'm not specifically interested in datetime. I was wondering about objects in general.

推荐答案

我的猜测是,日期时间的使用实施的 __ slots__中获得更好的性能。

My guess, is that the implementation of datetime uses __slots__ for better performance.

在使用 __ __插槽,跨preTER储备储存刚刚上市的属性,没有别的。这给了更好的性能,使用更少的存储空间,但也意味着你不能随意增加新的属性。

When using __slots__, the interpreter reserves storage for just the attributes listed, nothing else. This gives better performance and uses less storage, but it also means you can't add new attributes at will.

在这里阅读更多:<一href=\"http://docs.python.org/reference/datamodel.html\">http://docs.python.org/reference/datamodel.html

这篇关于为什么我不能直接将属性添加到任何Python对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆