Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Hint: You can adjust the default video playback speed in your account settings.
Hint: You can set your subtitle preferences in your account settings.
Sorry! Looks like there’s an issue with video playback 🙁 This might be due to a temporary outage or because of a configuration issue with your browser. Please refer to our video player troubleshooting guide for assistance.

Exploring Multiple Constructors in Existing Python Classes

If you’d like to learn more about these examples, then check out:

00:00 Exploring Multiple Constructors in Existing Classes. The @classmethod decorator is used in several built-in and standard-library classes to provide multiple alternative constructors. In this section, you’ll learn about three of the most notable examples of these classes: dict, datetime.date, and pathlib.Path.

00:25 Dictionaries are a fundamental data type in Python. They’re present in every piece of Python code, either explicitly or implicitly. They’re also a cornerstone of the language itself because important parts of the CPython implementation rely on them.

00:40 You have several ways to define dictionary instances in Python. You can use dictionary literals, which consist of key-value pairs in curly brackets ({}).

00:49 You can also call dict() explicitly with keyword arguments or with a sequence of two-item tuples, for example. This popular class also implements an alternate constructor called .fromkeys().

01:02 This class method takes an iterable of keys and an optional value. The value argument defaults to None and works as the value for all the keys in the resulting dictionary. Now, how can .fromkeys() be useful in your code?

01:18 Let’s say you are running an animal shelter, and you need to build a small application to track how many animals currently live there. Your app uses a dictionary to store the inventory of animals.

01:31 Because you already know which species you are capable of housing at the shelter, you can create the initial inventory dictionary dynamically, as in the code seen on-screen.

01:50 In this example, you build an initial dictionary using .fromkeys(), which takes the keys from allowed_animals. You set the initial inventory of each animal to 0 by providing this value as the second argument to .fromkeys().

02:06 As you already learned, value defaults to None, which can be a suitable initial value for your dictionary’s keys in some situations. However, in this example, 0 is a convenient value because you are working with the number of individuals that you have from each species.

02:24 Other mappings in the standard library also have a constructor called .fromkeys(). This is the case with OrderedDict, defaultdict, and UserDict.

02:35 On-screen, you can see part of the source code of UserDict showing the implementation of .fromkeys(). Here, .fromkeys() takes an iterable and a value is arguments.

02:45 The method creates a new dictionary by calling cls. Then it iterates over the keys in iterable and sets each value to value, which defaults to None as usual. Finally, the method returns the newly created dictionary.

03:01 The datetime.date class from the standard library is another class that takes advantage of multiple constructors. This class provides several alternative constructors, such as .today(), .fromtimestamp(), .fromordinal(), and .fromisoformat().

03:16 All of them allow you to construct datetime.date objects using conceptually different arguments. On-screen, you’ll see a few examples of how to use some of those constructors to create datetime.date objects.

03:38 The first example uses the standard class constructor as a reference. The second example shows you how you can use .today() to build a date object from the current day’s date.

03:49 The rest of the examples show how datetime.date uses several class methods to provide multiple constructors. This variety of constructors makes the instantiation process pretty versatile and powerful, covering a wide range of use cases.

04:04 It also improves the readability of your code with descriptive method names.

04:11 Python’s pathlib module from the standard library provides convenient and modern tools for gracefully handling system paths in your code. If you’ve never used this module, then check out Python 3’s pathlib Module: Taming the File System.

04:29 The handiest tool in pathlib is its Path class. This class allows you to handle your system path in a cross-platform way. Path is another standard-library class that provides multiple constructors, in this case .home() and .cwd().

04:46 Let’s take a look at the first, Path.home(). This creates a path object from your home directory. Here’s the code snippet running on Windows …

05:05 and on macOS, which will look very similar on Linux.

05:13 The .home() constructor returns a new path object representing the user’s home directory. This alternate construction can be useful when you’re handling configuration files in your Python applications and projects.

05:27 Path also provides a constructor called .cwd(). This method creates a path object from your current working directory. Go ahead and give it a try!

05:39 In the next section of the course, you’ll take a look at the method mentioned earlier and described in PEP 443, single-dispatch generic functions.

Become a Member to join the conversation.