set 和 freezeset 的继承行为似乎不同
有人可以解释以下行为:令
class derivedset1(frozenset):
def __new__(cls,*args):
return frozenset.__new__(cls,args)
class derivedset2(set):
def __new__(cls,*args):
return set.__new__(cls,args)
a=derivedset1('item1','item2') # WORKS
b=derivedset2('item1','item2') # DOESN'T WORK
Traceback (most recent call last):
File "inheriting-behaviours.py", line 12, in <module>
b=derivedset2('item1','item2') # DOESN'T WORK
TypeError: derivedset2 expected at most 1 arguments, got 2
我惊讶的是,您可以更改冻结集的构造函数,而可变集的构造函数则不可能。
Can someone explain the following behaviour:
class derivedset1(frozenset):
def __new__(cls,*args):
return frozenset.__new__(cls,args)
class derivedset2(set):
def __new__(cls,*args):
return set.__new__(cls,args)
a=derivedset1('item1','item2') # WORKS
b=derivedset2('item1','item2') # DOESN'T WORK
Traceback (most recent call last):
File "inheriting-behaviours.py", line 12, in <module>
b=derivedset2('item1','item2') # DOESN'T WORK
TypeError: derivedset2 expected at most 1 arguments, got 2
This is surprising to me that you can alter the constructor of a frozen set whereas it is not possible for the constructor of a mutable set.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
来自 Python 文档:
set.__init__
仅采用一个参数,即一个指定初始设置内容的可迭代对象。因此,您应该添加自己的初始化程序,它接受所有附加参数并将它们提供为初始设置值:请注意,您应该覆盖
__init__
并避免实现__new__
,除非您想要实现对象缓存、单例或类似奇怪的东西。您的子类化适用于frozenset
正是因为frozenset
确实从对象缓存中获益,即 Python 解释器只需要一个frozenset
具有相同内容的两个frozenset
对象的实例。一般来说,您应该避免对内置类进行子类化,特别是如果您的语义不兼容(在本例中为
set([])
和衍生集2([])
返回完全不同的结果)。From the Python documentation:
set.__init__
only takes one argument, an iterable specifying the initial set contents. Therefore, you should add your own initializer which takes all additional arguments and supplies them as the initial set values:Notice that you should overwrite
__init__
and refrain from implementing__new__
unless you want to implement object caching, singletons, or similar weird stuff. Your subclassing works forfrozenset
precisely becausefrozenset
does profit from object caching, i.e. the Python interpreter only needs onefrozenset
instance for twofrozenset
objects with the same content.In general, you should refrain from sub-classing built-in classes, especially if your semantics are incompatible (in this case,
set([])
andderivedset2([])
return totally different results).