gpt4 book ai didi

python : Wrapper class and constructor parameters

转载 作者:太空宇宙 更新时间:2023-11-04 08:56:40 24 4
gpt4 key购买 nike

我想为 frozenset 创建一个简单的包装类来更改构造函数参数。这是我想出的(就像我在 Java 中所做的那样):

class Edge(frozenset):
def __init__(self, a, b):
frozenset.__init__(self, {a, b})

我想让 Edge(0,1) 创建frozenset({0,1})

但是,我得到这个错误:

>>>Edge(0,1)
TypeError: Edge expected at most 1 arguments, got 2

最佳答案

frozenset 是不可变的,因此您需要覆盖 __new__ 方法:

class Edge(frozenset):
def __new__(cls, a, b):
return super(Edge, cls).__new__(cls, {a, b})

参见 here .

关于 python : Wrapper class and constructor parameters,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29549838/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com