Methods and attributes
Add functionality to classes
When you create your own Python classes, you'll want them to store information and perform actions. This is where attributes and methods come in handy!
Attributes: storing data
Attributes are like variables that belong to an object. They hold data specific to that object. Think of them as characteristics.
class Dog:
def __init__(self, name, breed):
self.name = name # This is an attribute
self.breed = breed # This is another attribute
my_dog = Dog("Buddy", "Golden Retriever")
print(my_dog.name)Methods: adding behavior
Methods are functions that belong to an object. They define the actions an object can perform. They allow your objects to do things.
class Dog:
def __init__(self, name, breed):
self.name = name
self.breed = breed
def bark(self): # This is a method
print(f"{self.name} says Woof!")
my_dog = Dog("Buddy", "Golden Retriever")
my_dog.bark()Notice how methods always take self as their first parameter. This self refers to the object itself, allowing the method to access its own attributes (like self.name).
Common mistakes
- Forgetting
selfwhen defining or calling attributes/methods inside the class. - Trying to access an attribute or method that hasn't been defined for an object.
- Confusing class attributes (shared by all instances) with instance attributes (unique to each instance).
Practice
Try these exercises to lock in what you just learned.
What's next?
Now that you understand attributes and methods, you can start building more complex and interactive classes. Experiment with adding more data and actions to your objects.