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

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

    I'd use inheritance. Especially if there are going to be more differences than number of holes. Especially if Gouda will need to have different set of members then Parmesan.

    class Gouda(Cheese):
        def __init__(self):
            super(Gouda).__init__(num_holes=10)
    
    
    class Parmesan(Cheese):
        def __init__(self):
            super(Parmesan).__init__(num_holes=15) 
    

提交回复
热议问题