Okay, you've seen how to define a basic blueprint for objects using the class
keyword and how to create individual objects (instances) from that blueprint. But what makes these objects useful? Part of the answer lies in their ability to hold their own unique data. Think of an object like a specific entity, say, a particular customer in an online store. This customer object needs to store information specific to them: their name, email address, purchase history, etc. This data stored within an object is known as its attributes.
Attributes are essentially variables that belong to a specific instance of a class. They represent the state or characteristics of that particular object.
You can add attributes to an object after it has been created using simple dot notation. The syntax is object.attribute_name = value
. Let's revisit our simple Dog
class example:
# Define a simple class (blueprint)
class Dog:
# For now, this class definition is empty
pass
# Create an instance (an actual dog object)
my_dog = Dog()
# Now, let's give this specific dog some attributes
my_dog.name = "Fido"
my_dog.breed = "German Shepherd"
my_dog.age = 4
# Create another instance
another_dog = Dog()
another_dog.name = "Buddy"
another_dog.breed = "Golden Retriever"
another_dog.age = 2
In this code:
Dog
class. It's just a placeholder blueprint for now.Dog
objects: my_dog
and another_dog
.name
, breed
, and age
for each specific object using dot notation (my_dog.name = "Fido"
).Notice that my_dog
and another_dog
are separate objects created from the same Dog
class. Each one gets its own set of attributes. Setting my_dog.name
does not affect another_dog.name
at all. Attributes store the state specific to each individual instance.
Once attributes are assigned, you can access their values using the same dot notation: object.attribute_name
.
# Continuing from the previous example:
# Accessing attributes of my_dog
print(f"My dog's name is: {my_dog.name}")
print(f"Its breed is: {my_dog.breed}")
print(f"And it is {my_dog.age} years old.")
# Accessing attributes of another_dog
print(f"\nMy other dog's name is: {another_dog.name}")
print(f"Its breed is: {another_dog.breed}")
This code demonstrates retrieving the values stored in the attributes of each Dog
object.
Each
Dog
object (instance) maintains its own distinct set of attribute values, even though both were created from the sameDog
class blueprint.
Attributes like these are also commonly referred to as instance variables because they are variables that belong to a specific instance.
While assigning attributes directly like this works, it's often more organized and conventional to set up an object's initial attributes when the object is first created. Python provides a special method, __init__
, for exactly this purpose, which we will look at in the next section. Using __init__
ensures that every object created from the class starts with a defined set of initial attributes.
© 2025 ApX Machine Learning