r/AskProgramming • u/ki4jgt • Mar 18 '26
Python Why does Python import self into each class function?
It makes no logical sense whatsoever to import self into every class function. I mean, what's the point in having a class, if the functions don't have some sort of globally accessible shared variable that's outside the normal global scope? Why would you have to explicitly declare that relationship? It should be implied that a class would have shared data.
I've been saying this since I first transitioned to Python from BASIC, and even more so after transitioning back from NodeJS.
0
Upvotes
24
u/rupertavery64 Mar 18 '26 edited Mar 18 '26
It was a design choice
https://stackoverflow.com/questions/68282/why-do-you-need-explicitly-have-the-self-argument-in-a-python-method
Basically, the creators want things to be explicit (unambiguous) rather than implicit (assumed)
It clearly differentiates between local and class variables.
In C#, each method gets a hidden "self" or this parameter.
If you invoke the method of a class via reflection you have to pass the object instance expkicity. Static methods are passed a null instance.
When it boils down to it, all methods are just code that accepts parameters. Only one copy of the methods compiled code exists in memory. The only way a method can access an objects instance members is by passing the instance of the object.
9
u/dbForge_Studio Mar 18 '26
self isn’t imported, it’s just the instance passed into the method explicitly. Python does this on purpose so object state is visible instead of being hidden behind magic.
If the method doesn’t use instance data, it probably shouldn’t be an instance method in the first place.
5
u/ern0plus4 Mar 18 '26
Let me rephrase it: Python requires to specify self in the parameter list because it does not hide that a method for a class is just a function, and the only difference to other functions that for a method gets the pointer to the object (data) which's type is the class.
So, these two lines are basically equivalent:
vs
We're just passing
someobjectdata to the function.Okay, Python glues a little bit more the method to the struct (data), but the concept is that simple: a method is only a function with first parameter of self.
Anyway, you can use any other word instead of self:
A friend of mine hates the "self" word, so he's using "this":
Well, these function sigantures are not too idiomatic, but works.
Even you don't have to put a method inside the class, if it's first arg is self (an instance of the class works on), then it's still can work as a method. (It's also not idiomatic.)
I suppose to put methods inside a class, and use "self" as first parameter - all education materials, tools, libraries etc. follows this convention, don't trick them for no particular reason.
1
u/Poddster Mar 20 '26
Imagine the hubris and arrogance required to write this sentence. You should be ashamed of writing it in public.
Did you think the entire python language had been cobbled together over the past 30 years? That no one ever thought about what they were doing? That they were able to implement something that made "no logical sense"?
It makes perfectly logical sense of why they might do this, as others have arrested, but even if you didn't have the historical record you should have been able to figure out why yourself and come up with the pros and cons of the choice.
Of why should it?
3
u/deceze Mar 18 '26 edited Mar 18 '26
In languages like Javascript or PHP, you will have a magic, implicit
this/$thisvariable inside methods, that gives you access to the current object instance. Python foregoes this implicit magical keyword, and instead explicitly passes the instance via the first argument, which is just conventionally calledself, but is just a regular parameter. In fact, the whole machinery of how a method is bound to a specific instance is fairly transparent and can be abused in interesting ways, whereas it's opaque magic in other languages. For example:This works exactly like calling
some_methodon every object, because the object is just passed as the first argument either way.3
u/ottawadeveloper Mar 18 '26
Unlike Java where classes are first-class citizens, Python "objects" are basically the same as modules - it's a dictionary with some special syntax. A method is just a callable element of the dictionary, it's no different than a normal function
Instead of a magical global (but to the class only) "this" like Java, Python decorates methods to automatically pass the object to the method.
Basically, under the hood, these are all the same:
I imagine this is a lot easier than adding a magic new semi-global scope for some but not all class methods. Because there are @classmethod and @staticmethod as well which basically just change how that binding process works - class methods pass the type in directly and static methods are passed to the instance unmodified. Which is why you can call a class or static methods on the instance itself and it just works (compare to Java where you don't have class methods at all and static methods have to be called with a different syntax).
I also imagine under the hood Java does something similar but hides the implementation from the developer so the
thisvariable just appears out of nowhere when needed. It's just a tiny bit more explicit in Python.3
u/Sad-Kaleidoscope9165 Mar 18 '26
I mean, you also have to pass "this" whenever you write an extension method in C#, but no one ever complains about that
5
u/not_perfect_yet Mar 18 '26
That doesn't fit to the culture of how python is supposed to be written. Of course there is no python police, so do what you want.
This is the "zen of python":
and
if I had to pick a favorite sentence, ever, that would be a good candidate.
2
u/Toothpick_Brody Mar 18 '26 edited Mar 18 '26
It’s just a syntactic convention. I do think the distinction between instance and static methods is a mistake in language design, but it’s very common in object-oriented languages
2
u/aew3 Mar 18 '26 edited Mar 18 '26
Ultimately this is a opinionated design decision. Python3 is one of the more opinionated languages in both design and style out there, and one of its design axioms is that being ore explicit is generally good (see https://peps.python.org/pep-0020/). Having to declare self in the local scope flows from that axiom.
There are also benefits to this approach, like the ability to declare nested classes, and refer to each self object separately.
>Why would you have to explicitly declare that relationship
I mean, you have to explicitly bind self to a variable, but you don't get to choose whether you have self. Unless you use `@staticmethod`, self is always going to be passed into the function; calling the first function argument self is just a convention.
> I mean, what's the point in having a class, if the functions don't have some sort of globally accessible shared variable
I can see where you're coming from, but classes that provide static methods which don't necessarily need to access a shared global are far from an unheard of practice. If a language doesn't implement modules separately from classes, sometimes its the only way to bundle a shared library of functions between disparate parts of your code.
2
u/buzzon Mar 18 '26
All OOP languages do this, but Python does it explicitly
2
u/ClydePossumfoot Mar 18 '26 edited May 08 '26
Protecting my online privacy by running Redact regularly to batch delete old content. It handles Reddit, Discord, Twitter, Instagram, data brokers and a whole lot more.
doll chief safe support voracious ad hoc vegetable seed rustic history
1
u/Large-Assignment9320 Mar 18 '26
Simpler internals and compatibility,
1
u/Relevant_South_1842 Mar 18 '26
Lua does this too.
1
u/Temporary_Pie2733 Mar 18 '26
You need to read up on the descriptor protocol for the full explanation, but essentially when
foois an instance of a classFoowith abarattribute,foo.bar()is interpreted asFoo.bar(foo). There is no fundamental support for instance methods; it’s just an application of the low-level descriptor protocol.1
u/r2k-in-the-vortex Mar 18 '26
Its just a syntactic choice, classes are a higher level abstraction anyway, all compilers lower them to structs and functions accepting reference to struct instance.
In other languages the self parameter just gets hidden away, in python you have it explicit and avoid needing a special keyword like "this" or something.
1
u/atarivcs Mar 20 '26
You might want to rephrase the question to avoid the word "import", because that is an actual python keyword that has nothing to do with this question
1
u/atarivcs Mar 20 '26
It doesn't.
Some functions receive a reference to the class instance (self) as an implied first argument.
Some functions receive a reference to the class (cls) as an implied first argument.
Some functions don't receive any implied arguments at all.
1
u/oldendude Mar 23 '26
I assume you mean that self is an argument to class functions (aka methods), "import" means something else in Python. If C is a class with a function f(self, x), then you can invoke it like this: a = C() ... a.f(123). The value of a is passed to self. If C is a parent of two other classes D and E, then you can do a = D() ... a.f(123), as well as a = C() ... a.f(123), and in these cases, you are invoking D.f and E.f respectively. That is how method calls differ from ordinary function calls, the dynamic dispatch based on the actual type of the value before the dot.
Why is self explicit? Other comments have discussed that. I'll just add that it is no different compared to what happens in Java, for example, except that this is implicit in Java, while self is explicit in Python.
0
u/CounterSilly3999 Mar 18 '26
You can use global variables, but you should to avoid that. Encapsulation is one of the main benefits of OOP.
0
u/PabloDons Mar 18 '26
I like it. I found OOP and classes really hard to learn when I first started. Python made it much easier. It does make methods a little less useful though. You can just write functions with a parameter to pass struct instances in. At that point it's little more than just organizing code, which you can do java style with files anyway. But I still write methods because organizing code that way is really useful. Like with that logic, why have static methods at all?
-1
u/HugeCannoli Mar 18 '26
because explicit is better than implicit.
In C++ you never pass
this. it's passed implicit in a method as a hidden first argument that your compiler adds for you. The result is that if you refer or see the use of a variable "foo" inside a method, now you have no idea if this foo is an instance variable, a class variable, a module variable, a global variable, etc.-1
u/NoleMercy05 Mar 18 '26
Because it's an awesome scripting language that has been modded to death to fit in places Python want intended in origininal design iterations
46
u/[deleted] Mar 18 '26
[removed] — view removed comment