Defining Multiple Constructors
00:25 Some programming languages, such as C++, C#, and Java, support what is known as function or method overloading. This feature allows you to provide multiple class constructors because it enables you to create multiple functions or methods with the same name and different implementations.
00:42 Method overloading means that depending on how you call the method at hand, the language will select the appropriate implementation to run. So, your method can perform different tasks according to the context of the call. Unfortunately, Python doesn’t support function overloading directly.
Python classes keep method names in an internal dictionary called
.__dict__, which holds the class namespace. Like any Python dictionary,
.__dict__ can’t have repeated keys, so you can’t have multiple methods with the same name in a given class.
In this example, you call
greeter, which is an instance of the
Greeter class. You get
Hello, Pythonista instead of
Hello, World on your screen, which confirms that the second implementation of the method prevails over the first one.
Something similar occurs with functions in a Python module and an interactive session. The last implementation of several functions with the same name prevails over the rest of the implementations. You define two functions with the same name,
say_hello() in the same interpreter session.
03:00 Another technique that some programming languages use to provide multiple ways to call a method or function is multiple dispatch. With this technique, you can write several different implementations of the same method or function and dynamically dispatch the desired implementation according to the type or other characteristics of the arguments that are used in the call.
03:20 You can use a couple of tools from the standard library to pull this technique into your Python code. Python is a fairly flexible and feature-rich language and provides a couple of ways to implement multiple constructors and make your classes more flexible.
Become a Member to join the conversation.