Skip to main content
Stack Overflow
  1. About
  2. For Teams

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

How to avoid explicit 'self' in Python?

I have been learning Python by following some pygame tutorials.

Therein I found extensive use of the keyword self, and coming from a primarily Java background, I find that I keep forgetting to type self. For example, instead of self.rect.centerx I would type rect.centerx, because, to me, rect is already a member variable of the class.

The Java parallel I can think of for this situation is having to prefix all references to member variables with this.

Am I stuck prefixing all member variables with self, or is there a way to declare them that would allow me to avoid having to do so?

Even if what I am suggesting isn't pythonic, I'd still like to know if it is possible.

I have taken a look at these related SO questions, but they don't quite answer what I am after:

Answer*

Draft saved
Draft discarded
Cancel
2
  • 2
    self is a way to tell the access modifier without really using one. +1 Commented Dec 31, 2009 at 5:57
  • 1
    This is for whoever reads this. self is not part of the python syntax. It's just a variable name. You can use any name you want. Also, python methods when called, are always implicitly passed with at least one argument in the first spot. That argument is the instance. That's why it gives you an error if you forget to define a parameter. Commented Oct 22, 2022 at 3:49

lang-py

AltStyle によって変換されたページ (->オリジナル) /