Overloading Constructors
Overloading Constructors
Overloading Constructors
Overloading constructors
Hi r/Python I'm working on a script to load a number of datasets into my field format. So the submitted data
sets may not or may not have all the fields available in my dataset. So I would like to make overloaded
constructors similar to a method in Java, to accommodate the variability in the field information they have.
def __init__(field1):
self.field1 = field1
def__init__(filed1, field2):
self.field1 = field1
self.field2 = field2
Thanks
5 comments
33% Upvoted
Sort by: best
level 1
Kopachris
3 points · 4 years ago
Python doesn't do function overloading like other languages do. Do as /u/anossov said and use default
arguments.
level 1
[deleted]
3 points · 4 years ago
Do missing fields have default values? If so, default arguments make the most sense:
1
Overloading constructors
level 1
bheklilr
0 points · 4 years ago
A common implementation (i.e. one used in the standard library) is to use staticmethods for multiple
constructors (which admittedly isn't quite the same as overloaded constructors):
class MyClass(object):
# The default constructor
def __init__(self, field1, field2, field3):
self.field1 = field1
self.field2 = field2
self.field3 = field3
@staticmethod
def only_field1(field1):
return MyClass(field1, None, None)
@staticmethod
def missing_field3(field1, field2):
return MyClass(field1, field2, None)
You can see this in particular with the datetime.datetime class, since it has a default constructor taking a
time representation, but there's also datetime.now and datetime.today where both have unique behavior.
In your case, since you just have 1, 2 or 3 fields you can get away with just using keyword arguments with
default values:
class MyClass(object):
def __init__(self, field1, field2=None, field3=None):
self.field1 = field1
self.field2 = field2
self.field3 = field3
level 2
donnieod
3 points · 4 years ago
I think that classmethod is the preferred way of doing this, if you look up datetime.today() and
datetime.now() they are classmethods not staticmethods. So your alternate constructors would be:
@classmethod
def only_field1(cls, field1):
return cls(field1, None, None)
@classmethod
def missing_fiels3(cls, field1, field2):
return cls(field1, field2, None)
This has the advantage of not locking in the class name so sub-classing is possible.