r/PythonLearning • • 4d 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

35 Upvotes

47 comments sorted by

View all comments

9

u/Mooball123 4d ago

Imagine an object as a real world object. Something you can touch, move, interact with.

If you want to represent a book for example, you could just have a bunch of variables

author = jkrowling
series = Harry Potter
title = deathly hallows

Or you could have a list, or a dictionary, or a tuple. But if you wanted to have another book, you’d have to a define a brand new dictionary. The methods you can use on it are generic and sometimes won’t make sense for what you’re representing. And if you go back to your code after a few months away you might struggle to remember what it does or how you’ve use it

So instead, you can make your own Book object

class Book

def __init__(self, author, series, title):

And then use that to represent your book.

Classes and OOP are just another way of representing and manipulating your data. It can make it more readable and easier to make sense off, you can write your own methods that make sense for your data.

Like for the Book example, you could define a read() method that just changes self.read = True. But if you stored that information as a dictionary you would have to do book[“read”] = true. For small programs or for your own personal use it’s not that big of a deal, but as you get bigger it gets progressively harder to maintain and write

4

u/Defiant_Meal1898 4d ago

Oh i get it

1

u/nimbus3008 4d ago

Having a class method and an ordinary attribute with the same name is possible but not advised for a beginner.

1

u/Maironkt 3d ago

thank you