属性分配内置对象 [英] Attribute assignment to built-in object

查看:131
本文介绍了属性分配内置对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

本作品:

class MyClass(object):
    pass

someinstance = MyClass()
someinstance.myattribute = 42
print someinstance.myattribute
>>> 42

但是,这并不:

someinstance = object()
someinstance.myattribute = 42
>>> AttributeError: 'object' object has no attribute 'myattribute'

为什么呢?我有一种感觉,认为这是反对是一个内置类有关,但我觉得这是不能令人满意的,因为我在MyClass的声明改变了什么。

Why? I've got a feeling, that this is related to object being a built-in class, but I find this unsatisfactory, since I changed nothing in the declaration of MyClass.

推荐答案

的Python存储在一个字典属性。您可以添加属性 MyClass的,看到它有一个 __ __字典

Python stores attributes in a dict. You can add attributes to MyClass, see it has a __dict__:

>>> class MyClass(object):
>>>   pass
>>> dir(MyClass)
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__']

重要的区别是,对象没有 __ __字典属性。

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

更详细的解释:

  • Can't set attributes of object class
  • Why can't you add attributes to object in python?

这篇关于属性分配内置对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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