繁体   English   中英

Python:使用dict派生类 - self = {的奇怪行为

[英]Python: Use of dict derived class - strange behavior of self={

A级和B级有什么区别?

自我有什么问题?

为什么我需要逐行声明自己?

class A(dict):
  def __init__(self):
    self={1:"you", 2:"and me"}
    print "inside of class A",self
class B(dict):
  def __init__(self):
    self[1]="you"
    self[2]="and me"
    print "inside of class B",self

a=A()
print "outside of class A",a
b=B()
print "outside of class B",b

结果:

inside of class A {1: 'you', 2: 'and me'}
outside of class A {}
inside of class B {1: 'you', 2: 'and me'}
outside of class B {1: 'you', 2: 'and me'}
  def __init__(self):
    self={1:"you", 2:"and me"}

这不会修改作为self传递的对象,而是将局部变量self重新绑定到新的dict。

正如其他人所说,分配给self是没用的,因为它只会改变局部变量的值而不会影响正在构造的dict。 你想要的是:

self.update({1:"you", 2:"and me"})

甚至:

dict.__init__(self, {1:"you", 2:"and me"})

如果你真的想有超过哪个实例类构造函数返回的控制(例如,为了实现例如缓存), 查找__new__

在A类中,您将分配给本地self变量。 当调用__init__self包含一个引用,所以构造的对象。 你将它重新分配给其他东西; 这根本不会改变A类的实例

事实上,如果你在A类上定义一个新方法,你会发现你分配给self的dict甚至在那里都看不到。 __init__回归的那一刻,它变得没有引用。

只是添加其他好的答案。 你可以看到字节码的区别:

A字节码:

Disassembly of __init__:
  3           0 BUILD_MAP                2
              3 LOAD_CONST               1 ('you')
              6 LOAD_CONST               2 (1)
              9 STORE_MAP           
             10 LOAD_CONST               3 ('and me')
             13 LOAD_CONST               4 (2)
             16 STORE_MAP           
             17 STORE_FAST               0 (self)  # stores values in local variable
                                                   # i.e not changing the object at all

  4          20 LOAD_CONST               5 ('inside of class A')
             23 PRINT_ITEM          
             24 LOAD_FAST                0 (self)
             27 PRINT_ITEM          
             28 PRINT_NEWLINE       
             29 LOAD_CONST               0 (None)
             32 RETURN_VALUE        

None

B字节码:

Disassembly of __init__:
  8           0 LOAD_CONST               1 ('you')
              3 LOAD_FAST                0 (self)  #loads self, i.e instance of dict
              6 LOAD_CONST               2 (1)
              9 STORE_SUBSCR                       #store value in it   

  9          10 LOAD_CONST               3 ('and me')
             13 LOAD_FAST                0 (self)
             16 LOAD_CONST               4 (2)
             19 STORE_SUBSCR        

 10          20 LOAD_CONST               5 ('inside of class B')
             23 PRINT_ITEM          
             24 LOAD_FAST                0 (self)
             27 PRINT_ITEM          
             28 PRINT_NEWLINE       
             29 LOAD_CONST               0 (None)
             32 RETURN_VALUE        

None

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM