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

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

    Using num_holes=None as the default is fine if you are going to have just __init__.

    If you want multiple, independent "constructors", you can provide these as class methods. These are usually called factory methods. In this case you could have the default for num_holes be 0.

    class Cheese(object):
        def __init__(self, num_holes=0):
            "defaults to a solid cheese"
            self.number_of_holes = num_holes
    
        @classmethod
        def random(cls):
            return cls(randint(0, 100))
    
        @classmethod
        def slightly_holey(cls):
            return cls(randint(0, 33))
    
        @classmethod
        def very_holey(cls):
            return cls(randint(66, 100))
    

    Now create object like this:

    gouda = Cheese()
    emmentaler = Cheese.random()
    leerdammer = Cheese.slightly_holey()
    
    0 讨论(0)
提交回复
热议问题