开发者

In Python difference in __dict__ between object() and class myClass(object)

I was messing around with dynamic attributes and I noticed I could not use the __dict__ attribute if I created the object directly from the object() class but if I create a new class that i开发者_高级运维s a direct descendent of object I can access the __dict__ attribute. Why the difference?

Examples:

# This gives an AttributeError  
o = object()
o.__dict__
# This works: prints {}
class myClass(object):
    pass
o = myClass()
o.__dict__


object is implemented in C and doesn't have a __dict__ attribute. (Not all Python objects have it either; look up __slots__).


I'm not entirely sure why it works for your class but not the original object class. I'd assume that when your class get initialized, it creates __dict__.

Using this code:

class Test(object):
    def __init__(self):
        pass

def main():
    print 'OBJECT:', dir(object())
    print
    print 'TEST:', dir(Test())
    return

Came up with this output:

OBJECT: ['__class__', '__delattr__', '__doc__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__']

TEST: ['__class__', '__delattr__', '__dict__', '__doc__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', '__weakref__']

As you can see, __dict__, __module__, and __weakref__ are in the Test object but not the base object

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜