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

后端 未结 13 2367
醉梦人生
醉梦人生 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:26

    Those are good ideas for your implementation, but if you are presenting a cheese making interface to a user. They don't care how many holes the cheese has or what internals go into making cheese. The user of your code just wants "gouda" or "parmesean" right?

    So why not do this:

    # cheese_user.py
    from cheeses import make_gouda, make_parmesean
    
    gouda = make_gouda()
    paremesean = make_parmesean()
    

    And then you can use any of the methods above to actually implement the functions:

    # cheeses.py
    class Cheese(object):
        def __init__(self, *args, **kwargs):
            #args -- tuple of anonymous arguments
            #kwargs -- dictionary of named arguments
            self.num_holes = kwargs.get('num_holes',random_holes())
    
    def make_gouda():
        return Cheese()
    
    def make_paremesean():
        return Cheese(num_holes=15)
    

    This is a good encapsulation technique, and I think it is more Pythonic. To me this way of doing things fits more in line more with duck typing. You are simply asking for a gouda object and you don't really care what class it is.

提交回复
热议问题