你为什么不能添加属性在python对象? [英] Why can't you add attributes to object in python?

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

问题描述

(用Python写的外壳)

(Written in Python shell)

>>> o = object()
>>> o.test = 1

Traceback (most recent call last):
  File "<pyshell#45>", line 1, in <module>
    o.test = 1
AttributeError: 'object' object has no attribute 'test'
>>> class test1:
    pass

>>> t = test1()
>>> t.test

Traceback (most recent call last):
  File "<pyshell#50>", line 1, in <module>
    t.test
AttributeError: test1 instance has no attribute 'test'
>>> t.test = 1
>>> t.test
1
>>> class test2(object):
    pass

>>> t = test2()
>>> t.test = 1
>>> t.test
1
>>>

为什么不反对让你的属性添加到它?

Why doesn't object allow you to add attributes to it?

推荐答案

注意的对象实例没有 __字典__ 属性:

>>> dir(object())
['__class__', '__delattr__', '__doc__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__']

一个例子来说明在派生类中这一行为:

An example to illustrate this behavior in a derived class:

>>> class Foo(object):
...     __slots__ = {}
...
>>> f = Foo()
>>> f.bar = 42
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'Foo' object has no attribute 'bar'

从文档报价在 插槽

[...]的 __ __插槽声明发生在每个实例的实例变量和储备序列刚好足够的空间容纳每个变量的值。因为 __ __字典为每个实例不创建节省空间。

[...] The __slots__ declaration takes a sequence of instance variables and reserves just enough space in each instance to hold a value for each variable. Space is saved because __dict__ is not created for each instance.

编辑:从意见回答ThomasH,OP的测试类是旧式级。尝试:

To answer ThomasH from the comments, OP's test class is an "old-style" class. Try:

>>> class test: pass
...
>>> getattr(test(), '__dict__')
{}
>>> getattr(object(), '__dict__')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'object' object has no attribute '__dict__'

,你会发现有一个 __ __字典实例。对象类可能不会有一个 __插槽__ 中定义的,但结果是一样的:缺乏一个 __字典__ ,这是什么prevents属性的动态分配。我改组我的回答让这个更清楚(移动第二段顶部)。

and you'll notice there is a __dict__ instance. The object class may not have a __slots__ defined, but the result is the same: lack of a __dict__, which is what prevents dynamic assignment of an attribute. I've reorganized my answer to make this clearer (move the second paragraph to the top).

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

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