1

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? (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.

Community
  • 1
  • 1
VectorVictor
  • 820
  • 8
  • 17
  • 1
    What are you expecting `random(100)` to do? If you import `random` and replace the calls with `random.randint(0,100)` your code works fine. – Daniel Roseman Feb 20 '16 at 14:16
  • I get: `NameError: name 'random' is not defined`. – Mike Müller Feb 20 '16 at 14:32
  • I was expecting a `TypeError` because `random` takes not argument or `NameError` if you didn't import `random` So your code can't produce that error message – styvane Feb 20 '16 at 14:33

1 Answers1

1

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
Mike Müller
  • 82,630
  • 20
  • 166
  • 161
  • I am still getting the same error? if you try either command: emmentaler = Cheese.random() or leerdammer = Cheese.slightly_holey(), it does not work – VectorVictor Feb 20 '16 at 14:31
  • Just copy my solution into a new file and run from the command line. – Mike Müller Feb 20 '16 at 14:34
  • @VectorVictor It's not clear what you are doing wrong. This code works. – chepner Feb 20 '16 at 14:39
  • Thank you everyone for your help. My problem goes away if I run the code as file. However if I paste into Ipython, it doesn't. I don't understand why exactly, but I don't want to waste more peoples time. Thanks – VectorVictor Feb 20 '16 at 18:22