Checking Types Explicitly: Code
00:00
Okay, so the first thing that you can try is the isinstance()
function. This way, you’ll only be using the swim()
method if the bird in question is a duck.
00:11
So for bird
in birds
, if
isinstance(bird,` Duck)
, meaning if the bird you’re looping through is from the Duck
class, then this bird can swim.
00:24
So bird.swim()
. And there you go. You get The duck is swimming
without any errors. You could also explicitly check if the current object or bird actually has the method that you’re trying to use on it.
00:40
You can use the hasattr()
function for this. So for bird
in birds, if hasattr(bird,
00:51
"swim")
, meaning if the bird in question has a swim()
method, then bird.swim()
. Let’s run this, and you get the same thing, The duck is swimming
without any errors.
01:06
As you might have noticed, going with the hasattr()
function gives you a more generic solution than isinstance()
. And even though checking the type of an object before using it can be a good solution in some cases, it’s not always the best approach.
01:22 One of Python’s coolest characteristics is its flexibility with types, and checking types all the time isn’t exactly a flexible thing to do.
01:32 In the next few lessons, you’ll learn about more ways to handle situations like this.
Become a Member to join the conversation.