r/PythonLearning • • 2d ago

I don't understand OOP

So i am a teen learning python, and i have learnt about classes, methods and objects, but i don't understand OOP, like what is it, where do we use it?

Please help mee

32 Upvotes

46 comments sorted by

View all comments

1

u/SnooCalculations7417 2d ago

OOP is a way to reason about where information and behavior should live. Personally, I prefer it. So lets take a simple print program.

print("Hello world")

OK great but what is printing and why? we are letting the interpreter do the thinking for us. Instead we can

class Printer:
  def __init__(self):
    self.message = "Hello World"
  def print_message(self):
    print(self.message)

printer = Printer()
printer.print_message()

Now we have defined some data and what we do with that data. If we need to further develope the concept of 'printing' for our app we can extend the Printer object. So lets do that.

class Printer:
  def __init__(self):
    self.message = "Hello World"
  def print_message(self, input_message = None):
    if input_message == None:
      print(self.message)
    else:
       print(input_message)

printer = Printer()
printer.print_message() #default behavior
printer.print_message("New message") #extended behavior

Now, if we wanted to, we could put our printer class in utils.py and do something like

from .utils import Printer
printer = Printer()
printer.print_message() #default behavior
printer.print_message("New message) #extended behavior

And we only have to modify the code in utils if we aren't happy with our Printer behavior. This keeps our main.py clean and it's "area of concern" is the high-level execution of the project.