[Tutor] Why is the name "self" optional instead of mandatory?

boB Stepp robertvstepp at gmail.com
Wed Jan 20 22:42:29 EST 2016


I'm whizzing along in "Python Crash Course" and am in the chapter on
classes.  Just to satisfy my suspicion that "self" is just a
placeholder for creating an object instance, I tried the following:

>>> class Dog(object):
        def __init__(this, name, age):
            this.name = name
            this.age = age
        def bark(this):
            print("Woof!  Woof!  Grrr!!!")
        def whoami(this):
            print("My name is", this.name.title(), "and I am",
                 this.age, "years old.")

>>> mydog = Dog('Spotty', 50)
>>> mydog.bark()
Woof!  Woof!  Grrr!!!

>>> mydog.whoami()
My name is Spotty and I am 50 years old.

And just to be really silly:

>>> class Cat(object):
        def __init__(MEOWWWW, name, age):
            MEOWWWW.name = name
            MEOWWWW.age = age
        def happy_cat(MEOWWWW):
            print("Zzzz ... purrrr ... zzzz")
        def whoami(MEOWWWW):
            print("My name is", MEOWWWW.name, "and I am", MEOWWWW.age,
                 "years old.  Now leave me be!  I'm very sleepy!!!")

>>> mycat = Cat('Callie', 7)
>>> mycat.happy_cat()
Zzzz ... purrrr ... zzzz
>>> mycat.whoami()
My name is Callie and I am 7 years old.  Now leave me be!  I'm very sleepy!!!

So I really only have one question:  Why not make Python's
*traditional* name, "self", mandatory?  Why give the programmer this
kind of choice?  [OK, that was two questions.]

TIA!
-- 
boB


More information about the Tutor mailing list