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

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

    All of these answers are excellent if you want to use optional parameters, but another Pythonic possibility is to use a classmethod to generate a factory-style pseudo-constructor:

    def __init__(self, num_holes):
    
      # do stuff with the number
    
    @classmethod
    def fromRandom(cls):
    
      return cls( # some-random-number )
    

提交回复
热议问题