Python Basics: Object Oriented Programming (OOP)
OOP Cheat Sheet (Extra)
Lesson 7 of 7 • 10 XP
Keep your place in this quest
Log in or sign up for free to subscribe, follow lesson progress, and access more learning content.
🐍 Python OOP Cheat Sheet
A quick reference for everything you’ve learned in the Python Basics: Object-Oriented Programming quest.
1. Classes and Objects
Defining a Class
class Person:
def __init__(self, name, age):
self.name = name # Public attribute
self.age = age # Public attribute
def greet(self):
print(f"Hello, my name is {self.name} and I am {self.age} years old.")
````
**Creating an Object**
```python
p1 = Person("John", 30)
p1.greet() # Hello, my name is John and I am 30 years old.
2. Attributes and Methods
- Attributes = variables that belong to an object (
self.attribute) - Methods = functions that belong to an object (
def method(self):)
Accessing:
print(p1.name) # Attribute
p1.greet() # Method
3. Inheritance
Basic Inheritance
class Animal:
def __init__(self, name):
self.name = name
def sound(self):
print("Some generic sound")
class Dog(Animal):
def sound(self):
print("Woof woof!")
dog = Dog("Rex")
dog.sound() # Woof woof!
4. super()
Calling Parent’s Constructor
class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name) # Call Animal's __init__
self.breed = breed
5. Method Overriding
Child classes can replace parent methods:
class Cat(Animal):
def sound(self):
print("Meow!")
6. Private Attributes & Methods
Mark as Private with __
class Person:
def __init__(self, name, age):
self.name = name
self.__age = age # Private attribute
def __print_age(self): # Private method
print(self.__age)
def show_info(self):
print(self.name)
self.__print_age()
Accessing private members directly will fail:
p = Person("Alice", 25)
p.__age # ❌ AttributeError
p._Person__age # ✅ Works, but not recommended
7. Key OOP Terms
| Term | Meaning |
|---|---|
| Class | Blueprint for objects. |
| Object | Instance of a class with its own data. |
| Attribute | Variable inside an object. |
| Method | Function inside a class. |
| Constructor | Special method __init__ called when creating an object. |
| Inheritance | Mechanism for reusing code from another class. |
| Overriding | Redefining a method from a parent class. |
super() |
Calls methods from the parent class. |
| Private | Prefixed with __ to indicate internal use only. |
8. Quick Best Practices
- Use PascalCase for class names:
MyClass - Use
selfto refer to the current object - Keep methods focused on one task
- Use private members for internal details
- Call
super().__init__()if you override__init__in a child class - Prefer composition or inheritance wisely — don’t inherit just for the sake of it
📌 Remember: OOP is about thinking in nouns (things) and their behaviors. Model real-world concepts, keep code organized, and reuse where possible.