user3236471
user3236471

Reputation:

Python : Wrapper class and constructor parameters

I would like to create a simple wrapper class for frozenset that changes the constructor arguments. Here is what I have come up with (as I would do it in Java) :

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

I would like to have Edge(0,1) createfrozenset({0,1}).

However, I get this error:

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

Upvotes: 1

Views: 407

Answers (2)

jwilner
jwilner

Reputation: 6606

This is a problem with the relationship between __new__ and __init__. You need to override __new__. Check out Python's use of __new__ and __init__?

Upvotes: 1

tzaman
tzaman

Reputation: 47860

frozenset is immutable, so you'll need to override the __new__ method:

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

See here.

Upvotes: 2

Related Questions