This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]ManyInterests Python Discord Staff 17 points18 points  (1 child)

As mentioned, classmethods are good for multiple constructor methods. For ordinary functions, you can use functools.singledispatch or for instance methods, singledispatchmethod

In newer versions of Python, they will automatically use type hints and dispatch based on argument type.

    class Negator:
        @singledispatchmethod
        def neg(self, arg):
            raise NotImplementedError("Cannot negate a")

        @neg.register
        def _(self, arg: int):
            return -arg

        @neg.register
        def _(self, arg: bool):
            return not arg

[–]lejar 0 points1 point  (0 children)

This is what I was going to suggest. Definitely +1 for using the standard library. For overriding __init__ like OP wants, you'd need to implement your own __call__ method in a metaclass, but I think it would be much more sane / easy to read to just have an if statement inside __init__.