r/learnpython • u/MonsieurBouclier • Mar 12 '24
Is python OOP the real thing ?
Hello, I'm currently writing a report on a project where I used python with the OOP paradigm and I want to be sure to not talk nonsense in it.
So, here is my question : Is python really fully respecting the OOP paradigm ?
I mean, for exemple when I want to make an abstract class, the concept doesn't really seem to exist. When I write an abstract method, I am obligated to use a decorator and it doesn't even prevent from calling the parent method. So i need to have a default behavior in it...
Also another question : I have seen that only mutable parameters can be updated in the body of a function. Is it specific to python or something generalized to other languages ?
9
u/Bobbias Mar 12 '24
OOP
The reply by u/cyberjellyfish is the best one as of writing this comment.
OOP is a nebulous concept, and modern definitions have strayed a fair bit from the intention of the creator.
However, ignoring that, Python still allows for modern OOP style programming.
It lacks some of the attributes some languages consider to be a core part of OOP, but that does not mean it automatically isn't OOP.
Abstract classes are nothing more than a class you cannot instantiate. From that perspective all your class needs to do is throw an exception when you try to instantiate it and it is now an abstract class.
The standard python equivalent to abstract classes (or interfaces, as they are sometimes referred to) are Protocols. Protocols cannot be instantiated by default (you could technically add __init__(), but that defeats the purpose of making it a Protocol in the first place).
If you have no default implementation for your abstract method, you raise a NotImplemented exception in the Protocol class definition, and leave it up to the subclasses to implement.
Python might not enforce the same rules that a language like Java, C++, or C# might, with regards to OOP, but that doesn't mean you can't write OOP code in Python.
Much of the difference with those languages comes from the fact that Python is dynamically typed. Consider the following code:
from typing import Protocol
class FooBar(Protocol):
def foo(self) -> str:
return "BAR1"
class A(FooBar):
pass
class B:
def foo(self) -> str:
return "BAR2"
def fun(val: FooBar) -> None:
print(val.foo())
fun(B()) # Prints "BAR2"This code is perfectly valid in python, because as the documentation I linked describes, python supports structural subtyping, meaning as long as B has whatever attributes FooBar describes, this code will function as expected, even if B was never explicitly named as a subtype of FooBar.
By comparison, this would not work in any of the previously mentioned static languages because none of them support structural subtyping. B would be required to explicitly derive from FooBar. That doesn't change the fact that we are passing one of two subtypes to a function which expects objects of the parent class, which is a pattern commonly used in OOP.
This demonstrates that while Python may be different from some of the languages people think of when they think of OOP these days, you can still program the same kind of code that you typically use in those languages. In fact, you are less restricted in some ways due to the structural subtyping.
Mutable parameters
Most functions don't change their arguments. Methods often change the instance they are attached to, but freestanding functions should generally speaking not change their arguments with minor exceptions. Even then, you don't strictly need to mutate the list. You could just as easily build a new one with the required changes instead and return that. If your function mutates its input, it becomes more difficult to reason about:
from typing import List
def foo(lst: List[int]) -> List[int]:
return [*lst, 5]
def bar(lst: List[int]) -> None:
lst.append(5)
the_list = [1, 2, 3, 4]
# return a new list
print(foo(the_list))
# mutate the_list in place
bar(the_list)
print(the_list)I would argue that foo makes a lot more sense than bar. It's more clear about what's happening (we're building a new list starting with the contents of the old one and inserting the value 5 at the end), and it creates a new object. We could replace the_list with if we wanted, or we could save it to a different variable, or pass it directly to another function as I do here.
With bar we have no such control, it mutates the_list and there is nothing we can do to avoid that. If we wanted to keep the original list around, we would need to copy it to another variable before calling bar. It's return type also tells us nothing useful. Since there's no documentation we'd need to go read the definition to see what it's even doing. If bar were a complex function which happens to work this way, it could take a fair bit of time to work out what's going on.
Of course, the other kind of mutable parameter is mutable default arguments, but those are a foot gun that you should generally avoid unless you absolutely need to use one. They are instantiated exactly once, at the beginning of the script, and their state persists throughout the entire life of the script. Any changes you make to a mutable default parameter persist between function calls (unlike local variables).
In the case of immutable values like Tuples, consider the following code:
the_tuple = (1, 2)
def foo(tpl: Tuple[int, int]) -> None:
tpl = (5, 5)
foo(the_tuple)
print(the_tuple) # prints (1, 2)At first glance it looks like this should work the same as changing the list in the function bar above, but because tuples are immutable, there is no way to mutate the value of a tuple once it's created. Any change to the_tuple must come from creating a new object and binding the name the_tuple to that new object, rather than modifying the existing object it points to at the start of the code.
1
u/MonsieurBouclier Mar 12 '24
Thank you for having taken the time to write this much of details in your answer, it was really heplful
1
2
25
u/cyberjellyfish Mar 12 '24
None of that is intrinsic to or requiref for OOP.
Hell, the modern Java-centric view of OOP is a departure from that the inventor intended (which was more about the message passing aspect than the structural aspects).
So, yes, python is "real" oop. So is Java. So is smalltalk. So is c with a bit of work.
8
u/ryo0ka Mar 12 '24
To the first question: Python is a multi-paradigm language with its own design choices. Regarding abstract methods, their design choice is “why not allow for default implementation?” because it opens up flexibility and, if you ever wish, it’s trivial to explicitly write down a “don’t call me” runtime exception in your abstract methods.
Is that OOP? I think so, they have their own design like any other languages do.
To the second question, immutable objects are common across the league. The idea dates back waaaay before Python.
2
u/reallyserious Mar 12 '24
it’s trivial to explicitly write down a “don’t call me” runtime exception in your abstract methods.
Yes. But when you do, all linters will complain. The linter won't know that you consider the method abstract.
6
u/Solonotix Mar 12 '24
So, here is my question : Is python really fully respecting the OOP paradigm ?
Yes. The history of Object-Oriented Programming (OOP) as a paradigm is generally considered to have its beginnings with the Smalltalk language in the 70s. A Smalltalk object can do exactly three things:
Hold state (references to other objects).
Receive a message from itself or another object.
In the course of processing a message, send messages to itself or another object.
The paradigm is focused on the practice of encapsulating data (or messages) within an "object", and then expressing actions (or methods) by way of passing messages between objects. The nature of OOP is to return nothing from a function/method, with the exception of status codes to represent conditional states upon completing an action. Even then, the state is contained within the objects, and you were supposed to pass objects to other objects, never working with primitives outside the object's implementation.
Python is a multi-paradigm language, in that it has functions as first class (allowing for strictly Functional Programming), but it also has a Data-Object Model for working in Object-Oriented Programming. Where it struggles is encapsulation. There are a few ways Python tries to hide things from the user, but ultimately there are no access modifiers (that I know of). As such, all members are technically available if you're clever (I say clever because prepending a member with double-underscore will mangle the name in an attempt to prevent outside access). Other languages with access modifiers have workarounds such as reflection, but Python will let you access a member if you know its name without any manipulation by the caller
2
u/Jello_Penguin_2956 Mar 12 '24
By your definition, child_instant.method_A would be the same as parent.method_A. It is not. Once instantiate, the method now is a part of child_instance and, if you do not override it, is default to take after its parent. That's what inheritance is. You are free to override it, or leave blank if you want to directly inherit from parent.
2
u/yvrelna Mar 12 '24
Every language has slightly different conception of OOP, and every programmers also has slightly different features that they want in their OOP language.
Python's object system sits squarely in one of the stronger OOP language. It has all the features you associate with OOP, everything in Python is an object.
One thing it doesn't do, is force OOP on everything. Python is a multiparadigm language. You can mix and match OOP, imperative, and functional approaches, depending on what the situation calls for.
A weaker variant of OOP is prototype-based language like JavaScript. Python clearly has stronger OOP than those variants.
A stronger level of OOP is like Java with objects having access protections, comprehensive built-in support for interfaces and abstract classes, but not everyone agrees that any of those features are even necessary for OOP.
But the original OOP, as it was originally conceived weren't even talking about any of these. The original OOP as it was in Smalltalk is about object actors passing messages to each other. Most modern languages simulates that with imperative function calls, but also they are not really.
Async programming with a bunch of coroutines communicating with one another via messages resembles a lot of that original OOP, but nobody really calls async programming OOP.
8
u/m0us3_rat Mar 12 '24
do you have a python specific question or just ramblings?
there are abstract classes or protocols
8
u/Mr_Lifewater Mar 12 '24
That tone is not very pythonic.
-4
u/m0us3_rat Mar 12 '24
sir yes sir.. i'mma be more careful next time i see your mom.
4
u/Mr_Lifewater Mar 12 '24
Neither is that. Are you even trying here?
-8
u/m0us3_rat Mar 12 '24
i do my best. did she say something?
4
2
-2
u/mfb1274 Mar 12 '24
class NotOop(metaclass=abc.ABCMeta): “””Ramblings from a college student who just read their professors self published Java book from the 1990s””” pass0
Mar 12 '24
[deleted]
0
u/m0us3_rat Mar 12 '24
the top comment put it very clearly..
How would you “update” a value that is immutable and therefore can’t change?
the OP doesn't seem to understand what is he trying to express.
he is using domain specific language without domain specific knowledge.
thus being.. clearly confused.
my pet peeve of ppl using words they don't necessarily understand..which sometimes i'm guilty myself..
just simplify. right?
to your point
Did you struggle to understand what they were asking?
Op didn't even understand himself what he was talking about.. so i get that you seem angry somehow..but i'm not sure exactly why.
whatever.
You can see other people had educational comments to make. I learned from them. Others learned from them. Whatever you wrote at the end there was pretty useless but stated like it’s some gift about to lead to an epiphany
that isn't accurate. the part about my comment..
as far as i understood.. OP claimed he can't make "abstract classes" in python..
which isn't true since you can use "protocol" or "abstract classes".
as i stated.
there are abstract classes or protocols
https://peps.python.org/pep-0544/#defining-a-protocol
https://docs.python.org/3/library/abc.html
they are completely different but also quite similar as far as "beginner" usability.
so, i actually gave a fairly direct response to what i believed OP was asking.
hope this clears it for you.
gl
1
u/Anon_Legi0n Mar 12 '24
In a way you can look at everything in python as an object, even primitives
1
1
Mar 12 '24 edited Mar 12 '24
Regarding your question about abstraction:
You could have you you class inherit from the AbstratctBaseClass module to do this. You figured out the decorator from the same module after all? (from abc import ABC).
The way it works and also with @abstractmethod is that it just prevents you from making instances of that class or method.
You could of course also do this manually if you wanted.
1
Mar 12 '24
I don't think OOP means anything anymore, so personally I would not mention this at all.
I don't really know exactly what you find lacking in the class system that needs to be there to be called OO. The only difference between java and python is that you can access any field and new classes can be created in the same file. Otherwise mixing data and functions is totally allowed using the class feature.
The original OO design had classes behave like state machines (like mini virtual computers) that can compute things internally and send messages to each other via an api. This design is terrible, which why no mainstream language does that.
I'm not sure what you mean by abstract class. Perhaps you mean what java might call an interface. Those exist as libraries in interface and typing. The usefulness of which is debatable. Since python is not statically typed, nor are interfaces used in the standard libs, you can't get the real deal from interfaces. For example, you can't just use the sort method by having a Compatible interface. Nor can you implement abstract functions that require an interface over types or classes.
To me, this says that python is not an OO language but does have OO features. But then, this begs the question, is something like Haskell and Rust OO because those do have interfaces and they are enforced even in the standard libs? This comes back to the beginning, what does OOP even mean?
0
Mar 12 '24
[deleted]
1
u/ImmediatelyOcelot Mar 12 '24
Nice! Now I'm angry this doesn't have more views...it's a perfect lunch break video...
0
u/m0us3_rat Mar 12 '24
I mainly wanted to take this opportunity to shill this video that only has 6k views that offends me its so under appreciated.
i hope you get banned for rule 4 break. probably not.
22
u/crashfrog02 Mar 12 '24
How would you “update” a value that is immutable and therefore can’t change?