Python : 包装器 class 和构造函数参数
Python : Wrapper class and constructor parameters
我想为 frozenset
创建一个简单的包装器 class 来更改构造函数参数。这是我想出的(正如我在 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。
这是__new__
和__init__
之间关系的问题。您需要覆盖 __new__
。查看 Python's use of __new__ and __init__?
我想为 frozenset
创建一个简单的包装器 class 来更改构造函数参数。这是我想出的(正如我在 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。
这是__new__
和__init__
之间关系的问题。您需要覆盖 __new__
。查看 Python's use of __new__ and __init__?