1

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
  • Can you show the full stack trace? Also, if all you want to do is change the way you construct the frozenset, why not define a two-argument ordinary function that returns a frozenset? – user2357112 Apr 09 '15 at 22:06
  • I want to be able to expand that class. –  Apr 09 '15 at 22:08

2 Answers2

2

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.

tzaman
  • 46,925
  • 11
  • 90
  • 115
1

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__?

Community
  • 1
  • 1
jwilner
  • 6,348
  • 6
  • 35
  • 47