Python语言问题:object()与Function的属性 [英] Python Language Question: attributes of object() vs Function

查看:306
本文介绍了Python语言问题:object()与Function的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在python中,为像这样的对象实例创建新属性是非法的。

 >>> a = object()
>>> a.hhh = 1

抛出

  Traceback(最近一次调用最后一次):
在< module>中,第1行的文件< stdin>
AttributeError:'object'对象没有属性'hhh'

然而,对于函数对象,这是OK。

 >>> def f():
... return 1
...
>>> f.hhh = 1

这种差异背后的基本原理是什么?


原因函数对象支持任意属性是因为在我们添加该特性之前,有几个框架(例如解析器生成器)函数对象)来存储对他们至关重要的每个函数的信息 - 需要将任意命名属性与函数对象的这种关联通过示例进行验证,直接用语言支持它们,而不是将文档串(例如文档串)为了支持任意实例属性,类型必须为它的每个实例提供一个 __ dict __ - 对函数来说没什么大不了的(反正它们从来都不是微小的对象),但是其他对象旨在很可能很小。通过使对象类型尽可能轻,并且还提供 __ slots __ 以允许避免每个实例<$ c在$ object 的子类型中,$ c> __ dict __ ,我们尽我们最大的努力支持小型专业值类型。 b $ b

In python, it is illegal to create new attribute for an object instance like this

>>> a = object()
>>> a.hhh = 1

throws

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'object' object has no attribute 'hhh'

However, for a function object, it is OK.

>>> def f():
...   return 1
...
>>> f.hhh = 1

What is the rationale behind this difference?

解决方案

The reason function objects support arbitrary attributes is that, before we added that feature, several frameworks (e.g. parser generator ones) were abusing function docstrings (and other attribute of function objects) to stash away per-function information that was crucial to them -- the need for such association of arbitrary named attributes to function objects being proven by example, supporting them directly in the language rather than punting and letting (e.g.) docstrings be abused, was pretty obvious.

To support arbitrary instance attributes a type must supply every one of its instances with a __dict__ -- that's no big deal for functions (which are never tiny objects anyway), but it might well be for other objects intended to be tiny. By making the object type as light as we could, and also supplying __slots__ to allow avoiding per-instance __dict__ in subtypes of object, we supported small, specialized "value" types to the best of our ability.

这篇关于Python语言问题:object()与Function的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
Python最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆