[Tutor] why "self" in methods? [compile-time vs run-time / pychecker]

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Mon Apr 5 14:54:55 EDT 2004



> The OP (me) is completely clueless at the moment, but I was asking about
> creating a method such as def noSelf() in your code below:
>
>  >>>>class SomeClass(object):
>  >
>  > ...     def sayHello(self):
>  > ...         print "hi, I'm SomeClass"
>  > ...     def noSelf():
>  > ...         print "I'm selfless"
>
> My original question was why, if it lacked a parameter, it didn't just
> automatically take the parameter self...


Hi Chris,


One possible reason is that 'self' isn't hardcoded into the language: we
can just as easily start using 'this' instead:

###
>>> class SomeClass(object):
...     def sayHello(this):
...         print "hi, I'm", this
...
>>> s = SomeClass()
>>> s.sayHello()
hi, I'm <__main__.SomeClass object at 0x400e694c>
###

The name that we use to pass around the instance is 'self' by community
convension --- there's no technical reason why it couldn't have been
'this'.




> that they can be created but not used doesn't seem very Pythonic :)

Python doesn't do much compile-time checking; in particular, it doesn't
check that we're sending the proper number of arguments to a function
until we actually try firing off the function:

###
>>> def hypo(a, b):
...     return (a**2 + b**2)**0.5
...
>>> def foo():
...     print hypo(3)
...
###


Notice here that we've just defined a function foo that tries to use
'hypo'... but we don't get an error yet!  But we will see an expected
error at "runtime":

###
>>> foo()
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "<stdin>", line 2, in foo
TypeError: hypo() takes exactly 2 arguments (1 given)
###



Going back to the original class example:

###
class SomeClass(object):
    def sayHello(self):
        print "hi, I'm SomeClass"
    def noSelf():
        print "I'm selfless"
###

one reason why Python doesn't report an error for noSelf() outright is
because it's not looking for parameter misuse at 'definition', or
'compile' time.


Although Python itself doesn't flag the missing 'self' as an error, there
are tools that will try to infer buggy usage.  PyChecker, in particular,
is a code-checking utility that detects these sort of problems:


###
class SomeClass(object):
    def sayHello(self):
        print "hi, I'm SomeClass"
    def noSelf():
        print "I'm selfless"
[dyoo at tesuque dyoo]$ pychecker foo.py
Processing foo...

Warnings...

foo.py:4: No method arguments, should have self as argument
###


PyChecker can be found here:

    http://pychecker.sourceforge.net/



Please feel free to ask more questions.  Hope this helps!




More information about the Tutor mailing list