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*

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
7
  • 13
    Brilliant! This is the most (only?) correct answer. +1 You also uniquely give a practical reason for doing it. +1i Commented Aug 16, 2018 at 15:20
  • 2
    After creating a class and moving the code inside of it : now all of the methods and variables are no longer recognized (no self. ..) I am reminded of yet another reason python and I do not get along. Thanks for this as an idea. It does not fix the problem /headache / unreadability overall but provides a modest workaround. Commented May 21, 2019 at 13:57
  • Why not just update locals instead of using exec? Commented Mar 13, 2020 at 17:14
  • 1
    I tried locals().update(self.__dict__) in python 2 and 3, but it didn't work. In python3 even the 'exec' trick isn't an option anymore. On the other hand, globals().update(self.__dict__) does work, but would be a terrible practice in general. Commented Mar 17, 2020 at 16:24
  • 5
    @WestCoastProjects I couldn't agree more. I believe in the principles outlined in "Clean Code" by Uncle Bob. And having "self." EVERYWHERE in my code DOES NOT make it any more readable or simple. Commented Sep 22, 2021 at 17:11

lang-py

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