Named Constructor in Python
posted at 01-07-2020
Sometime ago I had a need of creating a named constructor in Python, I looked up on some stuff and I did something like this:
class NamedConstructor:
def __init__(self, name: str, age: int):
self.name = name
self.age = age
def create_person_from_dict(person_data: dict):
return NamedConstructor(
name = person_data['name'],
age = person_data['age']
)
test = NamedConstructor.create_person_from_dict({'name': 'Airton', 'age': 24})
print(test.name)
## output: Airton
As I'm a noob Pythonist I accepted this solution, because this is pretty much what we do in PHP, as we can't create multiple constructors or multiple methods with same name and different signatures.
Something that I didn't know in the time is that Python has a decorator called @classmethod
, this, instead of accepting the argument self
- that points to the object instance - on the method, accepts cls
that points to the class.
Knowing that, we can rewrite this class as:
class NamedConstructor:
def __init__(self, name: str, age: int):
self.name = name
self.age = age
@classmethod
def create_person_from_dict(cls, person_data: dict):
return cls(
name = person_data['name'],
age = person_data['age']
)
test = NamedConstructor.create_person_from_dict({'name': 'Airton', 'age': 24})
print(test.name)
## output: Airton
There are some other usages for the @classmethod
, but used this decorator for it.
If you know some better way for do that or wants to talk more about this, send me a DM on twitter