What is a clean, pythonic way to have multiple constructors in Python?

后端 未结 13 2360
醉梦人生
醉梦人生 2020-11-22 07:12

I can\'t find a definitive answer for this. As far as I know, you can\'t have multiple __init__ functions in a Python class. So how do I solve this problem?

13条回答
  •  我寻月下人不归
    2020-11-22 07:28

    Why do you think your solution is "clunky"? Personally I would prefer one constructor with default values over multiple overloaded constructors in situations like yours (Python does not support method overloading anyway):

    def __init__(self, num_holes=None):
        if num_holes is None:
            # Construct a gouda
        else:
            # custom cheese
        # common initialization
    

    For really complex cases with lots of different constructors, it might be cleaner to use different factory functions instead:

    @classmethod
    def create_gouda(cls):
        c = Cheese()
        # ...
        return c
    
    @classmethod
    def create_cheddar(cls):
        # ...
    

    In your cheese example you might want to use a Gouda subclass of Cheese though...

提交回复
热议问题