python
Multiple constructors in python
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()
# another example
class C(object):
def __init__(self, fd):
# Assume fd is a file-like object.
self.fd = fd
@classmethod
def fromfilename(cls, name):
return cls(open(name, 'rb'))
# Now you can do:
c = C(fd)
# or:
c = C.fromfilename('a filename')
Was this helpful?
Similar Posts
- [Python] Different ways to test multiple flags at once in Python
- Python - regex , replace multiple spaces with one space
- [Python] Function returns multiple values
- Merge two or multiple dictionaries in Python
- Python program to return multiple values from a function
- Convert multiple spaces of a string to single space in python [with and without regex]
- Join two or multiple lists in Python