1

I want to create a class for numbers that takes ints, tuples, sets or lists. I tried using little knowledge I had of oop in python and this is what I could come up with as an __init__ method. But I don't think this is the way it is meant to be written. Also I can't iterate over my objects and when I print an object, I just get the object id. Do I have to write another method to be able to print it?

class Numbers():
    def __init__(self, num):
        assert isinstance(num, int) or isinstance(num, list) or isinstance(num, set) or isinstance(num, tuple), 'invalid numbers'
        if isinstance(num, int):
            self.num = int(num)
        elif isinstance(num, list):
            self.num = list(num)
        elif isinstance(num, tuple):
            self.num = tuple(num)
        elif isinstance(num, set):
            self.num = set(num)
>>>b = Numbers([1,2,3,4,5])
>>>b 
<__main__.Numbers object at 0x000001DF24F25250>
arty
  • 609
  • 1
  • 6
  • 12

1 Answers1

1

You just need to define a __repr__ method.

You may also want to check this.
Difference between __str__ and __repr__?

class Numbers():
    def __init__(self, num):
        assert isinstance(num, int) or isinstance(num, list) or isinstance(num, set) or isinstance(num, tuple), 'invalid numbers'
        if isinstance(num, int):
            self.num = int(num)
        elif isinstance(num, list):
            self.num = list(num)
        elif isinstance(num, tuple):
            self.num = tuple(num)
        elif isinstance(num, set):
            self.num = set(num)

    def __repr__(self):
        return self.num.__repr__()


b = Numbers([1,2,3,4,5])

print(b)
peter.petrov
  • 38,363
  • 16
  • 94
  • 159
  • Thanks for the `__repr__` part. But what about the first part? Is it "pythonic" to write `__init__` like that? – arty Mar 22 '20 at 19:56
  • 1
    @arthionne I am also not an experienced Python programmer so I am not 100% sure. I come from Java. But the `__init__` seems quite fine to me, I don't see anything wrong with it. The pattern you use is called "type-based dispatch". – peter.petrov Mar 22 '20 at 22:10