Search code snippets, questions, articles...

Multiple constructors in python

class Cheese(object):
    def __init__(self, num_holes=0):
        "defaults to a solid cheese"
        self.number_of_holes = num_holes

    def random(cls):
        return cls(randint(0, 100))

    def slightly_holey(cls):
        return cls(randint(0, 33))

    def very_holey(cls):
        return cls(randint(66, 100))

# Now create object like this:

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

# another example

class C(object):

    def __init__(self, fd):
        # Assume fd is a file-like object.
        self.fd = fd

    def fromfilename(cls, name):
        return cls(open(name, 'rb'))

# Now you can do:
c = C(fd)
# or:
c = C.fromfilename('a filename')
Best JSON Validator, JSON Tree Viewer, JSON Beautifier at same place. Check how cool is the tool
Was this helpful?