为什么我不能直接向任何 python 对象添加属性?

Why can#39;t I directly add attributes to any python object?(为什么我不能直接向任何 python 对象添加属性?)
本文介绍了为什么我不能直接向任何 python 对象添加属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我有这个代码:

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

还有这段代码:

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

根据我的 Python 知识,我会说 datetime 会覆盖 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?

我对 datetime 并不特别感兴趣.我想知道一般的对象.

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

推荐答案

我的猜测,是datetime的实现使用了__slots__ 以获得更好的性能.

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

当使用 __slots__ 时,解释器只为列出的属性保留存储空间,没有别的.这样可以提供更好的性能并使用更少的存储空间,但这也意味着您不能随意添加新属性.

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.

在此处阅读更多信息:http://docs.python.org/reference/datamodel.html

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

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How do I make a list of all members in a discord server using discord.py?(如何使用 discord.py 列出不和谐服务器中的所有成员?)
how to change discord.py bot activity(如何更改 discord.py 机器人活动)
Issues with getting VoiceChannel.members and Guild.members to return a full list(让 VoiceChannel.members 和 Guild.members 返回完整列表的问题)
Add button components to a message (discord.py)(将按钮组件添加到消息(discord.py))
on_message() and @bot.command issue(on_message() 和@bot.command 问题)
How to edit a message in discord.py(如何在 discord.py 中编辑消息)