Discussion - What's your go-to class identifier?

So I'm a little curious as to other's opinions on what I have loosely called a "class identifier" such as self in the following examples:

class Object:
    def __init__(self, parameter):
        self.parameter = parameter
        return

I ask because I know that the standard is considered to be self, but after taking a java course in university this semester I have found myself using 'this' as my class identifier in my python classes rather than 'self'. I just find that it's a better keyword to reference the current object you're working on. Would love to stir up some discussion and hear what the r/learnpython community consensus is regarding the topic.

Edit: originally put 'this' in the code example.. derp

Posted May 10, 2017, 2:42 AM UTC

26
cscanlincscanlin•

Please only use self in python (for everyone's sake). It's almost always better to use the convention of the language unless you have a very convincing reason not to (and following convention from a different language does not qualify).

8
doczillaOP•

That's a good point, the files I've included it in are really just personal scripts never really intended to be put out there at any point. I definitely agree with you as far as any code that is part of a large and/or public project

1
cscanlincscanlin•

Even in personal projects, you should always practice good habits!

This SO post gives a pretty convincing argument IMO of why to stick with it, and why it has to be explicitly set in python:

http://stackoverflow.com/a/37885900/1883900

And the blog post it links to by Guido van Rossum is excellent too:

http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay.html

EDIT:

And of course, all of this and more can be found in PEP 8

I would highly recommend using a linter like flake8 when starting out. There are linting plugins for all common text editors so it's easy to do real time. It will help keep your code much cleaner and easy to read.

5
doczillaOP•

Yeah, I was thinking about it more after my first reply and it would be incredibly easy to mix things up going between projects. After further review I think I'm definitely going to try to stick to the convention, thanks for the solid resources!

2
cscanlincscanlin•

No worries, and glad to hear it :)

Check out my edit to my last comment on PEP 8/linters too!

1
SaefrochSaethlin•

The consensus is self. Stick to the conventions of the language or project you're working on^([1]) or you will just confuse yourself and other developers (teammates, or people trying to help).


^([1]) Yes, even if you don't like them.

1