Skip to main content
 首页 » 编程设计

python : Wrapper class and constructor parameters

2025年05月04日110TianFang

我想为 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 .