我讀過為什么 Python 3.x 的 super() 魔術(shù)?并了解使用super或__class__在方法中將自動(dòng)__class__為該方法創(chuàng)建一個(gè)單元格變量:class Demo: def meth(self): super().meth()>>> Demo.meth.__closure__(<cell at 0x7f4572056138: type object at 0x564bda0e5dd8>,)>>> Demo.meth.__closure__[0].cell_contents<class '__main__.Demo'>據(jù)我所知,單元格用于保存閉包變量并且可以自由修改:def outer(): x = 3 def inner(): print(x) x = 5 return innerinner = outer()inner() # output: 5>>> inner.__closure__(<cell at 0x7f2183a5e138: int object at 0x7f2184600460>,)但是嘗試重新分配__class__單元格的值會(huì)super引發(fā)一個(gè)奇怪的錯(cuò)誤:class Demo: def meth(self): __class__ = Demo super().meth()Demo().meth()Traceback (most recent call last): File "untitled.py", line 8, in <module> Demo().meth() File "untitled.py", line 6, in meth super().meth()RuntimeError: super(): __class__ cell not found為什么會(huì)發(fā)生這種情況?為什么不能__class__像其他閉包變量一樣重新賦值?
添加回答
舉報(bào)
0/150
提交
取消