真的很奇怪...无法设置内置/扩展类型为'lxml.etree._Element'的属性 [英] Really weird... can't set attributes of built-in/extension type 'lxml.etree._Element'

查看:103
本文介绍了真的很奇怪...无法设置内置/扩展类型为'lxml.etree._Element'的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在没有问题之前,我已经更改了其他类的属性._Element显然不是内置的.

I've changed attributes for other classes before without issues. _Element is obviously not a built-in.

from lxml.etree import _Element
_Element.new_attr = 54

导致:

TypeError: 无法设置内置/扩展类型 'lxml.etree._Element' 的属性

TypeError: can't set attributes of built-in/extension type 'lxml.etree._Element'

推荐答案

_Element 史蒂夫·霍尔顿(Steve Holden)解释(我的重点),

_Element is implemented in Cython. As Steve Holden explains (my emphasis),

问题在于扩展类型的属性由对象插槽的布局,并永久固定在实现它们:插槽无法扩展,因此无法添加属性.这是一项效率功能:极端会很慢使用后期绑定查找基本类型的属性(它还会稍微改变语言的性质,使其更像Ruby或自我).

The problem is that extension types' attributes are determined by the layout of the object's slots and forever fixed in the C code that implements them: the slots can't be extended, so there's no way to add attributes. This is an efficiency feature: it would be extremely slow to look up the basic types' attributes using late-binding (it would also change the nature of the language somewhat, making it more like Ruby or Self).

和Guido van Rossum解释了为什么这是设计使然:

and Guido van Rossum explains why this is by-design:

这是有意禁止的,以防止意外的致命变化内置类型(对您从未使用过的部分代码具有致命影响的).另外,这样做是为了防止更改影响到不同由于内置类型,驻留在地址空间中的解释器(与用户定义的类不同)在所有此类对象之间共享口译员.

This is prohibited intentionally to prevent accidental fatal changes to built-in types (fatal to parts of the code that you never though of). Also, it is done to prevent the changes to affect different interpreters residing in the address space, since built-in types (unlike user-defined classes) are shared between all such interpreters.

这篇关于真的很奇怪...无法设置内置/扩展类型为'lxml.etree._Element'的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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