Python using classmethod for multiple constructors
Question: I have been struggling trying to create multiple constructors with the
classmethod decorator. There is an example in SO - [What is a clean, pythonic
way to have multiple constructors in
Python?](http://stackoverflow.com/questions/682504/what-is-a-clean-pythonic-
way-to-have-multiple-constructors-in-python) (second answer)

    
    
    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(random(100))
    
        @classmethod
        def slightly_holey(cls):
        return cls(random(33))
    
        @classmethod
        def very_holey(cls):
            return cls(random(66, 100))
    

However this example is not very clear and the code does not work for me in
python 3 when typing the commands given:

    
    
    gouda = Cheese()
    emmentaler = Cheese.random()
    leerdammer = Cheese.slightly_holey()
    

giving -

    
    
    AttributeError: type object 'Cheese' has no attribute 'random'
    

as this is one of the only examples I can find.


Answer: `randint` should work:

    
    
    from random import randint
    
    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))
    
    gouda = Cheese()
    emmentaler = Cheese.random()
    leerdammer = Cheese.slightly_holey()
    

Now:

    
    
    >>> leerdammer.number_of_holes
    11
    >>> gouda.number_of_holes
    0
    >>> emmentaler.number_of_holes
    95
    

