Introduction
In this lab, you will learn how to check if an object has a certain method in Python. The lab covers object methods, focusing on how they encapsulate behavior within objects for organized and reusable code.
You'll explore the Dog class with methods like __init__, bark, and get_name, creating instances and calling these methods. The lab will then guide you through using hasattr() and callable() to determine if an object possesses a specific method. Finally, you'll gain an understanding of Method Resolution Order (MRO).
Learn About Object Methods
In this step, you will learn about object methods in Python. Methods are functions that are associated with objects. They are used to perform operations on the object's data. Understanding object methods is crucial for working with objects and classes in Python.
Let's start by creating a simple class called Dog:
class Dog:
def __init__(self, name, breed):
self.name = name
self.breed = breed
def bark(self):
return "Woof!"
def get_name(self):
return self.name
Create a file named dog.py in your ~/project directory using the VS Code editor. Copy and paste the above code into the dog.py file.
This class has three methods:
__init__: This is the constructor method. It is called when a new object of the class is created. It initializes the object's attributes.bark: This method returns the string "Woof!".get_name: This method returns the name of the dog.
Now, let's create an object of the Dog class and call its methods. Create a new file named main.py in the ~/project directory:
from dog import Dog
my_dog = Dog("Buddy", "Golden Retriever")
print(my_dog.bark())
print(my_dog.get_name())
Save the main.py file.
To run the main.py script, open your terminal and navigate to the ~/project directory:
cd ~/project
Then, execute the script using the python command:
python main.py
You should see the following output:
Woof!
Buddy
In this example, my_dog is an object of the Dog class. We are calling the bark and get_name methods on the my_dog object using the dot notation (.).
Object methods allow you to encapsulate behavior within objects, making your code more organized and reusable. They are a fundamental part of object-oriented programming in Python.
Check with hasattr() and callable()
In this step, you will learn how to use the hasattr() and callable() functions in Python. These functions are useful for inspecting objects and determining whether they have certain attributes or methods.
hasattr(object, attribute_name): This function checks if an object has a given attribute. It returnsTrueif the attribute exists andFalseotherwise.callable(object): This function checks if an object is callable (i.e., it can be called like a function). It returnsTrueif the object is callable andFalseotherwise.
Let's continue with the Dog class from the previous step. Open the dog.py file in your ~/project directory using the VS Code editor. The content should be:
class Dog:
def __init__(self, name, breed):
self.name = name
self.breed = breed
def bark(self):
return "Woof!"
def get_name(self):
return self.name
Now, let's create a new file named check_methods.py in the ~/project directory to demonstrate the usage of hasattr() and callable():
from dog import Dog
my_dog = Dog("Buddy", "Golden Retriever")
print(hasattr(my_dog, "name"))
print(hasattr(my_dog, "bark"))
print(hasattr(my_dog, "age"))
print(callable(my_dog.bark))
print(callable(my_dog.name))
Save the check_methods.py file.
In this example:
hasattr(my_dog, "name")checks if themy_dogobject has an attribute named"name". It will returnTruebecause theDogclass has anameattribute.hasattr(my_dog, "bark")checks if themy_dogobject has an attribute named"bark". It will returnTruebecause theDogclass has abarkmethod.hasattr(my_dog, "age")checks if themy_dogobject has an attribute named"age". It will returnFalsebecause theDogclass does not have anageattribute.callable(my_dog.bark)checks if themy_dog.barkattribute is callable (i.e., it's a method). It will returnTruebecausebarkis a method.callable(my_dog.name)checks if themy_dog.nameattribute is callable. It will returnFalsebecausenameis a string attribute, not a method.
To run the check_methods.py script, open your terminal and navigate to the ~/project directory:
cd ~/project
Then, execute the script using the python command:
python check_methods.py
You should see the following output:
True
True
False
True
False
These functions are useful for writing more robust and flexible code that can handle different types of objects and attributes.
Understand Method Resolution Order (MRO)
In this step, you will learn about Method Resolution Order (MRO) in Python. MRO is the order in which Python searches for a method in a class hierarchy. It is particularly important when dealing with multiple inheritance.
Let's create a new set of classes to illustrate MRO. Create a file named animal.py in your ~/project directory using the VS Code editor:
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return "Generic animal sound"
class Mammal(Animal):
def speak(self):
return "Generic mammal sound"
class Dog(Mammal):
def speak(self):
return "Woof!"
class Cat(Mammal):
def speak(self):
return "Meow!"
Save the animal.py file.
Now, let's create a new file named mro_example.py in the ~/project directory to demonstrate MRO:
from animal import Animal, Mammal, Dog, Cat
my_dog = Dog("Buddy")
my_cat = Cat("Whiskers")
print(my_dog.speak())
print(my_cat.speak())
Save the mro_example.py file.
In this example:
Animalis the base class with aspeakmethod.Mammalinherits fromAnimaland overrides thespeakmethod.Doginherits fromMammaland overrides thespeakmethod.Catinherits fromMammaland overrides thespeakmethod.
When you call my_dog.speak(), Python first looks for the speak method in the Dog class. If it doesn't find it there, it looks in the Mammal class, and then in the Animal class. This order is determined by the MRO.
To run the mro_example.py script, open your terminal and navigate to the ~/project directory:
cd ~/project
Then, execute the script using the python command:
python mro_example.py
You should see the following output:
Woof!
Meow!
Now, let's explore a more complex example with multiple inheritance. Create a new file named mro_complex.py in the ~/project directory:
class A:
def method(self):
return "A"
class B(A):
def method(self):
return "B"
class C(A):
def method(self):
return "C"
class D(B, C):
pass
d = D()
print(d.method())
print(D.mro())
Save the mro_complex.py file.
In this example:
- Class
Dinherits from bothBandC. - Both
BandCinherit fromA. - The
methodis defined in all three classesA,B, andC.
To run the mro_complex.py script, open your terminal and navigate to the ~/project directory:
cd ~/project
Then, execute the script using the python command:
python mro_complex.py
You should see the following output:
B
[<class '__main__.D'>, <class '__main__.B'>, <class '__main__.C'>, <class '__main__.A'>, <class 'object'>]
The output B indicates that the method from class B is called. The D.mro() method returns a tuple representing the method resolution order for class D. In this case, the MRO is D -> B -> C -> A -> object. This means that when you call d.method(), Python first looks for the method in class D, then in class B, then in class C, then in class A, and finally in the base class object.
Understanding MRO is essential for predicting the behavior of your code when using inheritance, especially multiple inheritance.
Summary
In this lab, the initial step focuses on understanding object methods in Python. It introduces the concept of methods as functions associated with objects, crucial for performing operations on object data. A Dog class is created with methods like __init__, bark, and get_name to demonstrate how methods encapsulate behavior within objects.
The lab then guides you through creating an instance of the Dog class and calling its methods using dot notation, illustrating how object methods contribute to organized and reusable code in object-oriented programming.



