我想它可能是类似的collections.namedtuple,但这更像是一个冻结的词典(一个半冻结的词典).不是吗?
A"frozendict"应该是一个冰冻的字典,它应该有keys,values,get,等,并支持in,for等等.
我有一个类:
class A:
def __init__(self):
self.data = {}
Run Code Online (Sandbox Code Playgroud)
在某些时刻我想禁止self.data字段修改.
我已阅读PEP-416拒绝通知,有很多方法可以做到这一点.所以我想找到它们是什么.
我试过这个:
a = A()
a.data = types.MappingProxyType(a.data)
Run Code Online (Sandbox Code Playgroud)
这应该工作,但首先,它的python3.3 +和第二,当我这样做"禁止"多次我得到这个:
>>> a.data = types.MappingProxyType(a.data)
>>> a.data = types.MappingProxyType(a.data)
>>> a.data
mappingproxy(mappingproxy({}))
Run Code Online (Sandbox Code Playgroud)
虽然如果mappingproxy({})我要"禁止"很多次,那会好得多.检查isinstance(MappingProxyType)是一个选项,但我认为可以存在其他选项.
谢谢
当我调用从构造函数重写的方法时,出现错误,提示缺少参数(由于子类需要第二个参数)。但是,我在 super() 中调用了该方法,那么为什么它不调用该方法的超类版本呢?
用一个简短的例子可以很好地说明这一点:
class A:
def __init__(self):
self.do()
def do(self):
print("A")
class B(A):
def __init__(self):
super().__init__()
self.do("B")
def do(self, arg2):
super().do()
print(arg2)
b = B()
Run Code Online (Sandbox Code Playgroud)
这是我得到的错误:
Traceback (most recent call last):
File "D:/Python/Advanced/randomStuff/supersub.py", line 19, in <module>
b = B()
File "D:/Python/Advanced/randomStuff/supersub.py", line 11, in __init__
super().__init__()
File "D:/Python/Advanced/randomStuff/supersub.py", line 3, in __init__
self.do()
TypeError: do() missing 1 required positional argument: 'arg2'
Run Code Online (Sandbox Code Playgroud)
看起来是调用B类中的do()方法,但我想调用A类中的do()方法。理想情况下,代码应该打印:
A
A
B
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?
python ×3
dictionary ×2
immutability ×1
inheritance ×1
overriding ×1
subclass ×1
superclass ×1