A class is a blueprint for creating objects. Think of it as a cookie cutter: the shape defines what every cookie looks like, but each individual cookie can be different.
Defining a class
class Dog:
pass
class Cat:
passBy convention, class names use CapWords: every significant word starts with a capital letter and there are no separators.
Dog is good; dog, dOG, or my_dog_class are not.Creating an instance
class Dog:
pass
dino = Dog()
rufus = Dog()Dog() creates a new object. dino and rufus are two separate instances of the same class.Calling the name like a function —
Dog() — produces an instance. Each call makes a brand-new, independent object. The variable on the left is just a label pointing to that instance.Instance attributes with self
class Dog:
def __init__(self, name):
self.name = name
dino = Dog('Dino')
rufus = Dog('Rufus')
print(dino.name)
print(rufus.name)__init__ runs when you create an instance. self is the specific object being built.self refers to this particular instance. When you write self.name = name, you are saying: "store this value on me, not on some other dog." Because every call gets its own self, each instance keeps its data separate.Accessing attributes with a dot
class Book:
def __init__(self, title):
self.title = title
code_book = Book('Python Basics')
print(code_book.title)code_book.title reads the attribute. Dot notation is how you reach into an object.