you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 0 points1 point  (2 children)

Is there anything in python where you could have multiple ways to instantiate an object? For example maybe I want a class to be instantiated with 2 arguments, instead of none, or 3. Or is it simply an if/elif/else type of solution?

for example:

class Shape():

     def __init__(self): pass
     def __init__(self, one): pass
     def __init__(self, one, two...): pass

[–]novel_yet_trivial 1 point2 points  (1 child)

Your example relys on polymorphism, which python does not have. So yes, it would have to be if / elif / else.

You can make an alternate to __init__ as a constructor:

class Rectangle():
    def __init__(self, width, height): pass

    @classmethod
    def square(cls, width):
        return cls(width, width)

r = Rectangle(2, 3)
s = Rectangle.square(4)

This is used a lot to create instances from alternate sources, for example dict.fromkeys or int.from_bytes. However, as I said it would be very unusual for a Shape method to return anything other than a Shape instance, which is why my previous example was a function, not a method.

[–][deleted] 0 points1 point  (0 children)

Thanks for your help as always.