CS_Handbook
  • Search
  • 1) What is a class?
  • 2) Creating an Object
  • 3) Add Data with the Method
  • 4) Add Behavior (Methods)
  • 5) Add more Logic
  • 6) Inheritance
  • 7) Polymorphism (Same Method, Different Behavior)
  • 8) Encapsulation
    • ✅ Object-Oriented Programming Core Pillars (OOP Summary)

1) What is a class?¶

If you want to build multiple cars, you don't write instructions from scratch everytime--- you use a blueprint

In [23]:
Copied!
class Car:
  pass
class Car: pass

This defined a class called Car. It doesn't do anything yet-- it's just an empty plan.

In [23]:
Copied!

2) Creating an Object¶

You use the blueprint to create real things --- objects

In [24]:
Copied!
my_car = Car()
my_car = Car()

Now my_car is an object (or instance) of the Car class. You can make more cars.

In [25]:
Copied!
another_car = Car()
another_car = Car()
In [25]:
Copied!

3) Add Data with the __init__ Method¶

Let's give each car some info, like color or brand.

In [26]:
Copied!
class Car:
  def __init__(self, brand, color):
    self.brand = brand
    self.color = color
class Car: def __init__(self, brand, color): self.brand = brand self.color = color

__init__: Special method that runs when an object is created.

self: Refers to the current object.

self.brand = brand: Saves the brand info in the object.

In [27]:
Copied!
# Now create a car:

my_car = Car("Toyota", "Red")
print(my_car.brand)
print(my_car.color)
# Now create a car: my_car = Car("Toyota", "Red") print(my_car.brand) print(my_car.color)
Toyota
Red
In [27]:
Copied!

4) Add Behavior (Methods)¶

Classes can do things. Let's add a method.

In [28]:
Copied!
class Car:
  def __init__(self, brand, color):
    self.brand = brand
    self.color = color

  def drive(self):
    print(f"The {self.color} {self.brand} is driving")
class Car: def __init__(self, brand, color): self.brand = brand self.color = color def drive(self): print(f"The {self.color} {self.brand} is driving")
In [29]:
Copied!
# Use the method

my_car = Car("Honda", "white")
my_car.drive()
# Use the method my_car = Car("Honda", "white") my_car.drive()
The white Honda is driving
In [29]:
Copied!

5) Add more Logic¶

You can store static (info) and make changes:

In [37]:
Copied!
class Car:
  def __init__(self, brand, color):
    self.brand = brand
    self.color = color
    self.speed = 0

  def accelerate(self):
    self.speed += 10
    print(f"{self.brand} speed is now {self.speed} km/h.")

  def drive(self):
    print(f"{self.brand} is driving")
class Car: def __init__(self, brand, color): self.brand = brand self.color = color self.speed = 0 def accelerate(self): self.speed += 10 print(f"{self.brand} speed is now {self.speed} km/h.") def drive(self): print(f"{self.brand} is driving")
In [38]:
Copied!
# Use the method again

my_car = Car("Ferrari", "Red")
my_car.accelerate()
# Use the method again my_car = Car("Ferrari", "Red") my_car.accelerate()
Ferrari speed is now 10 km/h.
In [39]:
Copied!
my_car.accelerate()
my_car.accelerate()
Ferrari speed is now 20 km/h.
In [39]:
Copied!

6) Inheritance¶

Now you can make new classes based on old ones.

In [40]:
Copied!
class ElectricCar(Car):
  def charge(self):
    print(f"{self.brand} is charging.")
class ElectricCar(Car): def charge(self): print(f"{self.brand} is charging.")
In [41]:
Copied!
# let's call the new class

tesla = ElectricCar("Tesla", "black")
tesla.charge()
# let's call the new class tesla = ElectricCar("Tesla", "black") tesla.charge()
Tesla is charging.
In [42]:
Copied!
tesla.accelerate()
tesla.accelerate()
Tesla speed is now 10 km/h.
In [43]:
Copied!
tesla.drive()
tesla.drive()
Tesla is driving
In [43]:
Copied!

7) Polymorphism (Same Method, Different Behavior)¶

In [44]:
Copied!
class Animal:
  def speak(self):
    print("some sound")

class Dog(Animal):
  def speak(self):
    print("woof!")

class Cat(Animal):
  def speak(self):
    print("Meow!")
class Animal: def speak(self): print("some sound") class Dog(Animal): def speak(self): print("woof!") class Cat(Animal): def speak(self): print("Meow!")
In [45]:
Copied!
animals = [Dog(), Cat(), Animal()]
for a in animals:
  a.speak()
animals = [Dog(), Cat(), Animal()] for a in animals: a.speak()
woof!
Meow!
some sound

🤔 So Does Dog or Cat Overwrite Animal?¶

Not exactly. Here's what actually happens:

The Dog class inherits from Animal, meaning it starts with all of Animal's attributes and methods.

When you define speak() again in Dog, this is called overriding the method.

It does not overwrite the method in Animal; it replaces it only for objects of type Dog.

So when Python sees a.speak():

It checks the actual class of a.

If a is a Dog, it checks if Dog has a speak() method.

If found, it runs that and ignores the parent version.

If not found, it moves up to the parent, Animal, and uses that version.

🧬 Visualizing the Lookup (Method Resolution Order - MRO)¶

plaintext
Dog().speak()
↓
Look in Dog → Found! Use Dog's speak()


Cat().speak()
↓
Look in Cat → Found! Use Cat's speak()

Animal().speak()
↓
Look in Animal → Found! Use Animal's speak()

✅ Key Concept: Method Overriding ≠ Overwriting
Animal.speak() still exists.

Dog and Cat just override it when their own version is called.

This is the power of polymorphism—different behaviors for the same method name depending on the actual object type.

In [ ]:
Copied!

8) Encapsulation¶

Encapsulation means hiding the internal details of how an object works and exposing only what's necessary through public methods.

It helps:

  • Prevent accidental changes to internal data

  • Control access with getter/setter methods

  • Make code easier to maintain and debug

In [60]:
Copied!
class BankAccount:
  def __init__(self, balance):
    self.__balance = balance # Private variable

  def deposit(self, amount):
    self.__balance += amount

  def get_balance(self):
    return self.__balance
class BankAccount: def __init__(self, balance): self.__balance = balance # Private variable def deposit(self, amount): self.__balance += amount def get_balance(self): return self.__balance
In [61]:
Copied!
acct = BankAccount(100)
acct.deposit(50)
print(acct.get_balance())
acct = BankAccount(100) acct.deposit(50) print(acct.get_balance())
150
In [ ]:
Copied!

✅ Object-Oriented Programming Core Pillars (OOP Summary)¶

Encapsulation – Hiding the data (like private balance)

Inheritance – Child class inherits from a parent

Polymorphism – Same method name, different behavior

Abstraction – Hiding complexity and showing only essentials

In [ ]:
Copied!


Documentation built with MkDocs.

Search

From here you can search these documents. Enter your search terms below.

Keyboard Shortcuts

Keys Action
? Open this help
n Next page
p Previous page
s Search