Checking Argument Types
Checking Argument Types in
.__init__(). Another approach to simulate multiple constructors is to write a
.__init__() method that behaves differently depending on the argument type. To check the type of a variable in Python, you commonly rely on the built-in
You can also pass a tuple of types to this argument, allowing checking against the classes in the tuple and returning
True if any of them match. If you’re running Python 3.10 or later, then you can also use the new union syntax with the pipe symbol (
Your code will represent the birth date as a
date object, but for convenience your users will have the option of providing the birth date as a string with a given format. In this case, you can approach it in the way seen on-screen.
If so, then you define
.birth_date to store the date at hand. The
elif clause checks if the
birth_date argument is a string. If so, then you set
.birth_date to a
date object built from that provided string.
Note that the
birth_date argument should be a string with the date in ISO format year-month-date. And that’s it! You now have a
.__init__() method that simulates a class with multiple constructors.
03:31 But as you can probably see, the technique seen here has the drawback that it doesn’t scale well. If you have multiple arguments that can take values of different data types, then your implementation can soon become a nightmare.
Become a Member to join the conversation.