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
11
  • 6
    Thank you. This answer hits the spot cos it also explains the benefits of using self. Commented Jan 1, 2010 at 7:41
  • 4
    @Roger Pate: Please stop editing my question to remove python from it. I think that it belongs there. (and thanks for the answer!) Commented Nov 1, 2010 at 3:25
  • 3
    @bguiz: It's SO convention to not duplicate the tags in the title. However, when I edited 2 days ago, I did not see you reverted the title 7 months ago. Commented Nov 1, 2010 at 3:35
  • 11
    That's actually a rather silly-sounding reason. Python could fail to accept shadowing, and require you to declare it specifically, i.e. 'bless' your shadowing field with some kind of __shadow__ myFieldName. That would prevent accidental shadowing as well, wouldn't it? Commented Apr 9, 2015 at 19:17
  • 3
    @dwjohnston Ok, I am years late to the party, but I have just started learning Python (my background is C++), and I hate typing 'self'. However I do like explicitly distinguishing locals from instance data. Would a Syntax extension making '.' == 'self.' be feasible to allow code like: Commented Jun 20, 2018 at 1:11

lang-py

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