Classes & Objects
A class is a blueprint for creating objects. An object is an instance of a class with its own data (attributes) and behavior (methods).
Defining a Class
class Dog:
"""A simple Dog class."""
def __init__(self, name, breed, age):
"""Constructor — called when Dog() is invoked."""
self.name = name # instance attribute
self.breed = breed
self.age = age
def bark(self):
return f"{self.name} says: Woof!"
def birthday(self):
self.age += 1
return f"{self.name} is now {self.age} years old."Creating Instances
fido = Dog("Fido", "Labrador", 3)
bella = Dog("Bella", "Poodle", 5)
print(fido.name) # Fido
print(bella.bark()) # Bella says: Woof!
print(fido.birthday()) # Fido is now 4 years old.Accessing Attributes
print(vars(fido)) # {'name': 'Fido', ...}
print(hasattr(fido, "age")) # True
setattr(fido, "color", "golden")
print(fido.color) # golden