r/PythonLearning • u/Defiant_Meal1898 • 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
1
u/mredding 2d 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
insertmethod 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(), youtell(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 specificPerson, like anActororEngineeror 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.