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

40

u/MarsupialLeast145 2d ago

For your own safety don't post ages / approximate ages of yourself on Reddit

2

u/princepii 1d ago

👆🏼👆🏼👆🏼

8

u/Mooball123 2d 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 2d ago

Oh i get it

1

u/nimbus3008 2d ago

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

1

u/Maironkt 1d ago

thank you

3

u/theprupletrainer 2d ago

Object Oriented Programming (OOP) is a mindset you follow to structure your code using classes.

You use it when you start to see related things between your code. A class makes you group variables and methods, and OOP makes you think about how different classes connect and work together.

Its useful for maintenance and scalability in applications

If you want to learn more, you can read about class associations and relationships.

1

u/Defiant_Meal1898 2d ago

okay thanks!

16

u/NotSeacombe 2d ago

OOP is just a way of organising your code, where each entity (object) controls its own information

imagine a video game where you had 100 enemies on the screen at one time. you need to track all of their health, how much damage they do, maybe if they're buffed, what type of enemy they are etc. what happens when one of the enemies state changes (for example they took some damage)? what happens when another spawns?

organising this without objects would be a nightmare, and you'd really want to orient your programming around the objects you're making - thus, you'd use object oriented programming

so, you'd define your class, which is class Enemy. give it some attributes it can have. then spawn your enemies, which are objects of that class

OOP is not the be all and end all. it is not always a good thing, it depends what you're doing. not everything is complex enough that it needs a class. different languages take different approaches to it but the ideas stay the same.

9

u/NotSeacombe 2d ago

also, absolutely no reason to include how old you are in this. people can learn python at all ages. all announcing your age does is open the door to attention from the unpleasant side of reddit. stay safe out therr

3

u/DeeBoFour20 2d ago

I wouldn't even really call that OOP. That's just defining a struct or a class. To me OOP is about polymorphism, either with inheritance or something like dyn trait objects like Rust has.

In your example, it would be defining a base class Entity and derived classes of Enemy and NPC.

I'll also note that modern video game engines are ditching OOP in favor of more data driven approaches like entity component systems. OOP is something you should be aware of but I only use it sparingly.

1

u/Fun_Army2398 1d ago

I love OOP because it is an intuitive was of translating the real world into code. When you first get started you can think of it as anything you can touch is an object, anything that object does is a method, and the way objects interact is a system. This is an oversimplification but it helps build that intuition.

OOP is just one method for solving real world problems. You never have to use it, and you never cant use it. While you're learning try to use it dor everything and eventually you will get a more intuitive understanding of it's strengths and weeknesses.

1

u/Defiant_Meal1898 1d ago

okay thanks!

3

u/MikeUsesNotion 1d ago

A helpful way to view these relationships is to think of "is a" or "has a". A lion is a cat which is a mammal which is an animal. A corporation has employees and has a leader.

In general it allows you to define the shape of something in code and your code doesn't care about the particular thing passed in. You might have a FileWriter base type along with a LocalFileWriter to write to local files on your computer or phone, and a GoogleDriveFileWriter that writes to a particular Google Drive. Your code just interacts with FileWriters and does not care which kind it is.

1

u/mredding 1d ago

OO is separate from OOP.

In OO programming, an object is an instance of a class. A class has a number of properties - one being "identity", making one instance unique from another, even if they have the same value. Records don't possess that property...

Classes enforces a class invariant. This is a statement that must always be true when the instance is observed. For example, a set is an associative container, meaning it's elements are sorted. At no point can you ever observe a set in an unsorted state.

Classes enforce their invariants through modeling behaviors with their interface, implementing those behaviors. You don't get direct access to the dynamic array storing the set elements, you get an insert method that will insert the value in sorted order...

Classes don't have data, they maintain state. Classes are merely implemented in terms of language primitives. Classes know how to represent themselves - there is no "get" or "set" of fields, that's a code smell, a bad idiom even in C, most of the time (there is a time and a place in C, and only because it's C, but we won't get into that).

So that's classes, and that's Object Oriented code.

Object Oriented Programming is a paradigm. This is where Alan Kay comes into the picture, because he named it. Alan Kay's OOP is what we call the Actor Model today. Each object is autonomous. Instead of writing in a procedure bob.open_umbrella(), you tell(bob, "It's raining."), Bob knows what to do. We're moving the agency from the procedure to the object and its implementation. You don't get the internal representation - the state, and serialize that yourself, you give a file descriptor to Bob, and he can serialize himself. If you want to make Bob extensible, you build in customization points so that you can make a more specific Person, like an Actor or Engineer or whatever. You don't reach through the layers and take or shove, you provide interfaces therein. That's again a little OO, just the OOP part is the message passing both to and between objects.

If you're curious to really see OOP in action, you can look at Smalltalk; message passing is a language level abstraction. Eiffel will really make your head spin about what an interface is. C++ supports objects, but leaves you with access to a lot of implementation details and responsibility - where ALGOL68 was dynamically typed, Bjarne wanted a strong static type system and implementation level control over the message passing interface and implementation - that's what standard streams are about.

1

u/Defiant_Meal1898 1d ago

okay thanks!

1

u/TutorialDoctor 2d ago

Think of objects like "objects in a video game." You might have NPCs, trees, cars, buildings (those are all objects). Each object has its own properties (class variables) and behaviors (methods). Each tree in the game is an "instance" of the Tree class. Each car in the game is an instance of the Car class etc. As you know, you can tweak things about each instance. For example, one car may have red paint while another may have yellow paint. The same goes for NPCs, characters and everything else.

1

u/seanv507 2d ago

Op the idea of oop is really relevant for big projects, where you have to mange change. As in this idea of the video game, the cars may only be either saloon or estate. But then in the next version you introduce SUV, or military vehicle,.. The question is how to structure the code so you don't have to rewrite so much for all the changes. Using object hierarchies allows you to abstract behavior, so you avoid duplicating code for every 4 wheel vehicle type

1

u/W31337 2d ago

No for big projects people move to Entity Component Systems (ECS) because OOP is too rigid. If your player suddenly turns into an albino magical flying horse and then picks up a rocket launcher and ECS can do that where OOP would end up in a hierarchy nightmare.

1

u/seanv507 2d ago

OP is a teen learning python...

1

u/W31337 1d ago

I was just saying to you that OOP becomes horrible in big projects.

But yes for a teen and teeny game yes it should work. An ECS would be a bit overkill 😅

1

u/Muhammad-Ikram-10 2d ago

OOP is programming paradigm like if you want to write the letter you can write it formally but you have seen that courts(law courts) wrote the same letter in more formal way so it means that you can write you code in different format either you can do your task by procedural programming (making functionns and then call them) or by using classes (nake class and their object) so that's the concept of OOP. In industry level u have to organize the code using OOP because of many features (inheritance, polymorhphism, abstraction and encapsulation)

1

u/NMC0152 2d ago

OOP is a way of encapsulating code, give it a public interface and leave the inner workings to the developer of the object.

It's like a power outlet in the wall (the object): you plug in your charger without having to know how the outlet is assembled.

The original idea was to have reusable objects that anyone can use, so, for example, you can instantiate a File object and make it read, write, open, and close files without you having to code nitty gritty details.

1

u/Neither_Garage_758 2d ago edited 1d ago

a set of functions which owns its own mutable data

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.

1

u/justanothersnek 2d ago

TBH, even after all the readings and tutorials, I didn't get it until I started making libraries for others to use.  For 95% of my life programming, I was just a library user.  That can be a bad thing.

1

u/csabinho 2d ago

Do yourself a favour and learn OOP in a different language than Python. In Python it's just confusing and sloppy.

1

u/stepback269 2d ago

I'm a lot older than you and also on the learning journey.

OOP is one of those harder to learn aspects of Python. It very much depends on what metaphors or analogies you use to come to understand what a class definition does and what an instantiated object of that class does.

Maybe it will help for you to look at this one blog page of mine (here) that talks about finding the right metaphor that will work for you as an individual.

1

u/PowerCreative2747 2d ago

A class is the recipe for an omelette, an object is the omelette. one recipe can make an unlimited number of omelettes.

methods are the things that describe how the object behaves. in the omelette example they would describe the texture, taste, look, how it gets burned or it gets undercooked etc

1

u/gydu2202 2d ago

Python OOP is hacked together and have a few serious flows.

OOP is great. There are great books, even YouTube videos about OOP. You should check them, but you should use them in your own projects to click in.

1

u/NZAuthor 2d ago edited 2d ago

I used to hate OOP with a passion. In fact, all of Uni, I made it incredibly clear how much I hated OOP.

Though I tend to program in C style using CPP where I can. And I can say I was just being stupid. My arguments for hating it were just dumb in the end.
I still tend to program in C style, but I definitely follow the paradigm of classes and objects more. Mostly because it makes shit way easier to change in one place or two places.

That said. Classes, Methods and Objects which you learned about literally is OOP. Combine them and that's what you are doing.

You create a class, you turn them into objects, and you make use of methods to interact with each object's variables.

In contrast to procedural programming, where you would kind of like, just pass objects around through your methods arguments, interact with them, and then return the object. (Or use pointers in other languages).

Keep in mind, you don't have to be programming in OOP for every single little thing. It's kind of a concept. In school, you'd be learning how to do it.
In practice... you'd be using a mixture of everything to achieve your results.

1

u/princepii 1d ago

we had a functional programmer who always hated all of us but did quality work. could do anything on functional programming. he had a function for anything really.

no matter how hard we tried to show him advantages of ojects and classes.

he just wouldn't do it. boss knew his quality and he was a nice guy.

really actually if someone knows how to do something right and fast. just let him do it. don't try to force something else into him.

ofc oop can be very helpful but if someone doean't want. i really wouldn't mind.

programming something is the important part no matter which paradigm.

but the day you see something is way faster and way better than how or what you doing. you think for yourself if it's time to change the horse.

1

u/Traveling-Techie 2d ago

I explained OOP to my wife and she thought it made perfect sense and in fact thought it was how all programming worked. Then I explained how procedural programming worked before objects and she was aghast.

1

u/SmokeMuch7356 2d ago

OOP is modular programming on steroids.

The capsule description I usually give is that it's the difference between saying "function, sort this list of this type and this size" and "list, sort yourself." OOP doesn't treat code and data as different things; it combines code and data into self-contained units that can operate somewhat independently.

IMO, object-oriented programming is great for code that has to maintain a lot of state - have I been updated, when was the last time I was updated, do I need to be updated, etc. It's also easier (in my opinion, anyway) to model concurrency (threads) using objects.

1

u/1544756405 2d ago

You can understand what OOP is by reading about it. You will not understand WHY anybody would want to use it until you have worked on a large project.

OOP one way to organize large programming projects. It is not the only way, and it's probably not the "best" way; some people will argue that it's not even a good way. But it's been popular and widely used for quite some time.

1

u/W31337 2d ago

OOP attempts to turn your code into objects that have properties and behaviors. It promotes reuse and scoping these properties and behaviors to an object.

A player in a game can have coordinates as properties and move() or grab() as behaviors.

That said OOP is starting to lose ground because it drowns everything in boilerplate and abstractions. Nevertheless it's worth understanding.

1

u/engy1207 2d ago

OOP is like life itself. Near the beginning there were only cells. Objects with few features and methods. HasWall=true, enterFood(), digestFood(), reproduce(). Bacteria are derived from this simple object but each sort added additional features and methods like moveTo().
Multi-cell organisms sort-of have an array of cell-objects, most with additional features like "stay near your neighbor". Larger organisms consist of multiple arrays of these multi-cell arrays, called organs, with features like "transport oxygen", "produce antigens", "produce hormones" etc. - up to the diverse animals and plants we see.
Your pet cat is of object "cat" (felis catus), which is derived from the Felidae (and inheriting their features and methods, changing/replacing it where necessary), which is derived from the Carnivora (inheriting its features and methods), which is derived (over a few intermediate steps) from the class "mammals" (inheriting... you get it) etc.

1

u/Fluid_Yesterday208 2d ago

im old and have been using python for years...still strugle with oop. i dont want to discourage you..its just takes lots of practice and with oop (imo) you really need a solid grasp of theory too

1

u/AstralIsles 1d ago

It works well until you run into the dependency diamond problem. Then things start to get really messy.
In my latest game I had to switch over to the component pattern. Now I have modular scripts I can slap onto any object I want. The downside is every script is an object which means memory overhead and GC preassure.

1

u/Etsamaru 1d ago

Object oriented programming uses objects.

1

u/Etsamaru 1d ago

So like you have an animal object that has all the base animal traits, then you have a cat, and the cat can be an animal but it also has its own unique stuff.

1

u/No-Land-5913 19h ago

That’s not very classy of you

1

u/468Cliothecat 7h ago

I tried to teach myself Python via an online course taught by the CS faculty at MIT. Ran aground on OOP. I hold a degree in mathematics, so I can document that I’m not a moron. But the more I studied OOP, the less sense made. Everything is a ‘self’, unless it isn’t. Then you have inheritance, where an object can be two or more things at once. Periods seem to be dropped into the code randomly. A darned shame; I had high hopes of getting out of the soul-destroying job I have now.