Python Classes — Complete Cheat Sheet
What is a Class?
A class is a blueprint for creating objects. It defines the properties (variables) andmethods (functions) that objects created from it will have.
Think of a class as a template. Objects are individual copies created from this template.
Why Use Classes?
- Organize code into structures
- Reuse code easily
- Follow OOP (Object-Oriented Programming)
- Model real-world things like Car, Student, Product, etc.
Basic Class Syntax
A simple class with a class attribute:
class MyClass: x = 10
MyClass is a class. Inside it, x is a class attribute.
Creating an Object from a Class
obj = MyClass() print(obj.x)
obj is an object created from MyClass. Access its attributes using dot notation.
Class with a Method
A class can have functions called methods:
class Person:
def greet(self):
print("Hello, I am a Person")p = Person() p.greet()
Every method must include self as the first parameter. It refers to the current object.
Class vs Object
| Class | Object |
|---|---|
| Blueprint, template | Instance created from the class |
| Defines attributes + methods | Uses attributes + methods |
| Created once | Many objects can be created |
Best Practices
- Use PascalCase for class names (e.g., StudentData)
- Use self to access attributes inside methods
- Group related functions and data inside classes
- Keep class names meaningful and descriptive