实例dict和class dict之间有什么区别

时间:2013-02-10 07:06:53

标签: python

我正在阅读python描述符,那里有一行

  

Python首先在实例字典中查找成员。如果它是   没找到,它在班级词典中找到它。

我真的很困惑什么是实例字典和什么是类字典

任何人都可以用代码向我解释那是什么

我认为他们是同样的

6 个答案:

答案 0 :(得分:4)

我想,你可以用这个例子来理解。

class Demo(object):
    class_dict = {}   # Class dict, common for all instances

    def __init__(self, d):
        self.instance_dict = d   # Instance dict, different for each instance

并且总是可以像这样添加实例属性: -

demo = Demo({1: "demo"})
demo.new_dict = {}  # A new instance dictionary defined just for this instance

demo2 = Demo({2: "demo2"})   # This instance only has one instance dictionary defined in `init` method

因此,在上面的示例中,demo实例现在具有2实例字典 - 一个在类外添加,另一个在__init__方法中添加到每个实例。然而,demo2实例只有一个实例字典,在__init__方法中添加了一个。

除此之外,两个实例都有一个共同的字典 - 类字典。

答案 1 :(得分:3)

实例dict包含对分配给实例的所有对象和值的引用,类级别dict保存类命名空间中的所有引用。

采用以下示例:

>>> class A(object):
...    def foo(self, bar):
...       self.zoo = bar
...
>>> i = A()
>>> i.__dict__ # instance dict is empty
{}
>>> i.foo('hello') # assign a value to an instance
>>> i.__dict__ 
{'zoo': 'hello'} # this is the instance level dict
>>> i.z = {'another':'dict'}
>>> i.__dict__
{'z': {'another': 'dict'}, 'zoo': 'hello'} # all at instance level
>>> A.__dict__.keys() # at the CLASS level, only holds items in the class's namespace
['__dict__', '__module__', 'foo', '__weakref__', '__doc__']

答案 2 :(得分:1)

类dict在类的所有实例(对象)之间共享,而每个实例(对象)都有自己的实例dict的单独副本。

答案 3 :(得分:0)

您可以基于每个实例而不是整个类

分别定义属性

例如。

class A(object):
    an_attr = 0

a1 = A()
a2 = A()

a1.another_attr = 1

现在a2不会有another_attr。这是实例字典的一部分,而不是类字典。

答案 4 :(得分:0)

Rohit Jain有最简单的python代码来快速解释。但是,理解Java中的相同想法可能很有用,并且有关于类和实例变量的更多信息here

答案 5 :(得分:0)

这些dicts是表示对象或类范围命名空间的内部方式。

假设我们有一个班级:

class C(object):
    def f(self):
        print "Hello!"

c = C()

此时,f是类dict(f in C.__dict__中定义的方法,而C.f是根据Python 2.7的未绑定方法) 。

c.f()将执行以下步骤:

  • f中查找c.__dict__并失败
  • f中查找C.__dict__并成功
  • 致电C.f(c)

现在,让我们来做一个技巧:

def f_french():
    print "Bonjour!"

c.f = f_french

我们刚刚修改了对象自己的字典。这意味着,c.f()现在将打印Bounjour!。这不会影响原始的类行为,因此其他C的实例仍会说英语。