Introduction
In this lab, you will learn how to check if a class has a specific attribute in Python. The lab focuses on understanding class attributes, which are variables shared by all instances of a class, and differentiating them from instance attributes.
The lab guides you through creating a Dog class with a class attribute species and instance attributes name and age. You'll learn to access both types of attributes and observe how modifying a class attribute affects all instances. The lab will then introduce and utilize the hasattr() and getattr() functions to safely check for and access attributes within a class.
Understand Class Attributes
In this step, you will learn about class attributes in Python. Class attributes are variables that are defined within a class and are shared by all instances (objects) of that class. They are different from instance attributes, which are specific to each instance. Understanding class attributes is crucial for designing efficient and organized classes.
Let's start by creating a simple class with a class attribute:
Open your VS Code editor.
Create a new file named
class_attributes.pyin the~/projectdirectory.~/project/class_attributes.pyAdd the following code to the
class_attributes.pyfile:class Dog: species = "Canis familiaris" def __init__(self, name, age): self.name = name self.age = age ## Creating instances of the Dog class dog1 = Dog("Buddy", 3) dog2 = Dog("Lucy", 5) ## Accessing the class attribute print(dog1.species) print(dog2.species) ## Accessing instance attributes print(dog1.name) print(dog2.name)In this example,
speciesis a class attribute because it is defined within theDogclass but outside of any method.nameandageare instance attributes because they are defined within the__init__method and are specific to eachDoginstance.Run the
class_attributes.pyscript using the following command in the terminal:python class_attributes.pyYou should see the following output:
Canis familiaris Canis familiaris Buddy LucyAs you can see, both
dog1anddog2share the samespeciesvalue, which is "Canis familiaris". However, they have differentnamevalues becausenameis an instance attribute.Now, let's modify the class attribute and see how it affects the instances:
class Dog: species = "Canis familiaris" def __init__(self, name, age): self.name = name self.age = age ## Creating instances of the Dog class dog1 = Dog("Buddy", 3) dog2 = Dog("Lucy", 5) ## Accessing the class attribute print(dog1.species) print(dog2.species) ## Modifying the class attribute Dog.species = "New Species" ## Accessing the class attribute again print(dog1.species) print(dog2.species)Run the
class_attributes.pyscript again:python class_attributes.pyYou should see the following output:
Canis familiaris Canis familiaris New Species New SpeciesNotice that when we modify
Dog.species, the change is reflected in bothdog1anddog2because they share the same class attribute.
This example demonstrates the basic concept of class attributes. They are shared among all instances of a class and can be modified by accessing the class directly.
Use hasattr() on the Class
In this step, you will learn how to use the hasattr() function in Python to check if a class or an object has a specific attribute. This function is useful for determining whether an attribute exists before attempting to access it, which can prevent errors and make your code more robust.
Building upon the previous example, let's use hasattr() to check for the existence of class and instance attributes in the Dog class:
Open the
class_attributes.pyfile in your VS Code editor (the same file you created in the previous step).~/project/class_attributes.pyModify the code to include
hasattr()checks as follows:class Dog: species = "Canis familiaris" def __init__(self, name, age): self.name = name self.age = age ## Creating an instance of the Dog class dog1 = Dog("Buddy", 3) ## Checking for the existence of class attributes print(hasattr(Dog, "species")) print(hasattr(Dog, "breed")) ## Checking for the existence of instance attributes print(hasattr(dog1, "name")) print(hasattr(dog1, "age")) print(hasattr(dog1, "breed"))In this code, we use
hasattr()to check if theDogclass has thespeciesandbreedattributes, and if thedog1instance has thename,age, andbreedattributes.Run the
class_attributes.pyscript using the following command in the terminal:python class_attributes.pyYou should see the following output:
True False True True FalseThe output shows that the
Dogclass has thespeciesattribute (True) but not thebreedattribute (False). Similarly, thedog1instance has thenameandageattributes (True) but not thebreedattribute (False).
hasattr() returns True if the attribute exists and False otherwise. This allows you to write conditional code that handles different cases based on the presence of attributes. For example, you might want to provide a default value if an attribute is missing.
This example demonstrates how to use hasattr() to check for the existence of attributes in a class and its instances. This is a useful technique for writing more flexible and robust code.
Safely Access with getattr()
In this step, you will learn how to use the getattr() function in Python to safely access attributes of a class or an object. The getattr() function allows you to provide a default value if the attribute does not exist, preventing AttributeError exceptions and making your code more robust.
Continuing with the Dog class example, let's use getattr() to access the breed attribute, which we know might not exist:
Open the
class_attributes.pyfile in your VS Code editor (the same file you've been using in the previous steps).~/project/class_attributes.pyModify the code to include
getattr()to safely access thebreedattribute:class Dog: species = "Canis familiaris" def __init__(self, name, age): self.name = name self.age = age ## Creating an instance of the Dog class dog1 = Dog("Buddy", 3) ## Safely accessing the 'breed' attribute using getattr() breed = getattr(dog1, "breed", "Unknown") print(breed) ## Accessing existing attributes print(getattr(dog1, "name"))In this code, we use
getattr(dog1, "breed", "Unknown")to attempt to access thebreedattribute of thedog1instance. If thebreedattribute does not exist,getattr()will return the default value "Unknown". We also access the existingnameattribute usinggetattr().Run the
class_attributes.pyscript using the following command in the terminal:python class_attributes.pyYou should see the following output:
Unknown BuddyThe output shows that since the
breedattribute does not exist,getattr()returned the default value "Unknown". Thenameattribute is accessed successfully usinggetattr().
By using getattr() with a default value, you can avoid AttributeError exceptions and handle cases where an attribute might be missing. This makes your code more resilient and easier to maintain.
This example demonstrates how to use getattr() to safely access attributes in a class and its instances. This is a valuable technique for writing more robust and flexible code.
Summary
In this lab, you learned about class attributes in Python, which are variables defined within a class and shared by all instances. You created a Dog class with a class attribute species and instance attributes name and age. You observed that all instances of the Dog class share the same value for the species attribute, while each instance has its own unique values for the name and age attributes.
You also executed the class_attributes.py script and verified the output, confirming that class attributes are accessed in the same way as instance attributes but are shared across all instances of the class.



