Locked learning resources

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

Unlock This Lesson

Locked learning resources

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

Unlock This Lesson

Checking Types Explicitly

00:00 Checking the types of an object explicitly is another alternative to duck typing. This approach is more restrictive because it requires you to make sure the object is a specific type or has the necessary methods before using it in your code.

00:15 But what does it mean to check types explicitly? When you’re checking types explicitly, you’re checking an object’s type. Instead of assuming it has the right methods, you explicitly verify its type before using it.

00:29 You’re also making sure that it has the needed methods. Before calling a method, you check if the object actually supports it. Okay, now how are you supposed to do this?

00:41 First, if you want to check whether an object comes from a given class, you use the isinstance() function, and when you want to check whether an object has a specific method or attribute, you use the hasattr() function.

00:58 Let’s get practical. This code defines two classes, Duck and Pigeon, each with their own methods. Both classes have a .fly() method, meaning they can be used interchangeably when calling .fly() or in other words, they partially support duck typing, but the Pigeon class doesn’t have a .swim() method.

01:18 Let’s write some code to verify what happens. After you save your code, you can head to the terminal.

01:28 Okay, let’s import Duck and Pigeon first: from birds import Duck and Pigeon. Okay, let’s instantiate these classes and store them in a list called birds.

01:43 birds = [Duck(), Pigeon()]

01:50 Now let’s loop through them and use the .fly() method on them. for bird in birds: bird.fly(). It worked as expected.

02:03 The duck is flying, the pigeon is flying. But what happens if you use the .swim() method on the pigeon objects? Let’s see what happens: for bird in birds: bird.swim().

02:21 You get the duck is swimming, but you also get an AttributeError: 'Pigeon' object has no attribute 'swim'.

02:31 Let’s use type checking to avoid the AttributeError you just ran into in the previous example.

Become a Member to join the conversation.