Classes and Objects
Classes and Objects
Section titled βClasses and ObjectsβWhat it means
Section titled βWhat it meansβA class is a blueprint for creating objects β it bundles data (attributes) and behavior (methods) together. An object (or instance) is a concrete thing built from that blueprint. __init__ is the constructor, called automatically when you create a new instance, and self refers to the specific instance a method is operating on.
Examples
Section titled βExamplesβclass Dog: def __init__(self, name, breed): self.name = name self.breed = breed
def bark(self): return f"{self.name} says Woof!"
fido = Dog("Fido", "Labrador")print(fido.bark()) # Fido says Woof!print(fido.name) # Fido
class Counter: def __init__(self): self.count = 0
def increment(self): self.count += 1
c = Counter()c.increment()c.increment()print(c.count) # 2Common mistake
Section titled βCommon mistakeβForgetting self as the first parameter of an instance method, or forgetting to prefix attribute access with self. inside the class β both cause NameError or TypeError.
class Broken: def __init__(name): # missing self -- 'name' silently becomes self name = name # this is a local variable, not an attribute!
# Fixed:class Fixed: def __init__(self, name): self.name = name # self.name is the actual instance attributeQuick practice
Section titled βQuick practiceβ-
What does
selfrepresent inside a method?Answer
The specific instance the method is being called on β Python passes it automatically as the first argument. -
What is
__init__called for?Answer
It's the constructor β Python calls it automatically right after a new instance is created, to set up initial attribute values. -
What happens if you assign
name = nameinside__init__instead ofself.name = name?Answer
It creates/reassigns a local variable that disappears when the method returns β the instance never gets anameattribute.