Classes & Objects
The blueprint-and-instance model — __init__, self, and instance methods.
A class is a blueprint; an object (or instance) is a specific thing built from that blueprint. __init__ runs automatically when you create an instance, and self refers to the instance itself — it must be the first parameter of every instance method.
class YouTuber:
def __init__(self, channel_name, subscribers=0):
self.channel_name = channel_name
self.subscribers = subscribers
def upload_video(self):
self.subscribers += 100
return f"{self.channel_name} uploaded a video and gained subscribers!"
def describe(self):
return f"{self.channel_name} has {self.subscribers:,} subscribers"
munna = YouTuber("CodeWithMunnaX", 250_000)
print(munna.describe())
print(munna.upload_video())
print(munna.describe()) # subscribers went up — self.subscribers persists on the instance
Every attribute set on self (like self.channel_name) belongs to that specific instance — creating a second YouTuber gives it its own independent subscribers count.
harry = YouTuber("CodeWithHarry", 4_000_000)
print(harry.describe())
print(munna.describe()) # completely independent from harry's data
Class attributes vs. instance attributes
A class attribute is shared by every instance unless a specific instance overrides it; an instance attribute (set via self.x = ... in __init__) belongs to just that one object.
class YouTuber:
platform = "YouTube" # class attribute — shared by all instances
def __init__(self, channel_name):
self.channel_name = channel_name # instance attribute — unique per object
print(YouTuber("A").platform, YouTuber("B").platform) # YouTube YouTube
Methods vs. plain functions
A method is just a function defined inside a class — the only real difference is that Python automatically passes the instance as the first argument (self) when you call it via instance.method().
- •__init__ is the constructor — it runs automatically when you create a new instance of a class.
- •self refers to the specific instance a method was called on, and must be the first parameter of every instance method.
- •Attributes set via self.x in __init__ are unique per instance; class-level attributes (defined directly in the class body) are shared across all instances unless overridden.
- •Two instances of the same class are completely independent — changing one's attributes never affects the other.
A YouTuber class with independent instances
Revision Flashcards
Tap a card to flip it and see the answer.