Now that we understand classes as blueprints, let's delve into the fundamental components that define the characteristics and actions of our objects: attributes and methods. Think of attributes as the 'nouns' of your object – the data that describes it – and methods as the 'verbs' – the actions it can perform.
Attributes are variables that belong to an object. They hold the state or properties of an instance of a class. When you create an object from a class, each object gets its own copy of these attributes, which can have different values.
class Dog:
def __init__(self, name, breed):
self.name = name
self.breed = breedIn this Dog class, name and breed are attributes. The __init__ method (which we'll cover more in the next section) is where we often initialize these attributes when a new Dog object is created. The self keyword is crucial here; it refers to the instance of the class itself, allowing us to assign values to its attributes.
my_dog = Dog("Buddy", "Golden Retriever")
print(my_dog.name)
print(my_dog.breed)Here, we create an instance of the Dog class called my_dog. We then access its name and breed attributes using the dot notation (.). This demonstrates how attributes store the unique information for each object.
Methods, on the other hand, are functions defined within a class. They represent the behaviors or operations that an object can perform. Methods operate on the object's attributes, allowing the object to interact with its own data.
class Dog:
def __init__(self, name, breed):
self.name = name
self.breed = breed
def bark(self):
print(f"{self.name} says Woof!")
def describe(self):
return f"This is {self.name}, a {self.breed}."In this enhanced Dog class, bark and describe are methods. Notice that they also take self as their first parameter, allowing them to access and manipulate the object's attributes (like self.name and self.breed).