[Tutor] Why is the name "self" optional instead of mandatory?
Steven D'Aprano
steve at pearwood.info
Thu Jan 21 06:49:29 EST 2016
On Wed, Jan 20, 2016 at 09:42:29PM -0600, boB Stepp wrote:
> 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.]
Why bother making it mandatory? That just makes more work for the
compiler -- it has to decide that a function is inside a class, and
therefore apply a restriction to the first argument. Most of the time,
giving the programmer more freedom is less work.
And what happens if you do this?
class X:
pass
def func(this):
print("instance %r called method" % this)
X.method = func
And what are we supposed to do with classmethods and staticmethods? They
shouldn't take a "self" argument at all, but they start off life as a
regular function, just like ordinary instance methods.
And of course, there are Metaclasses. You might need a metaclass method
that needs to deal with all three levels of the hierarchy: the
metaclass, the class it creates, and the instance of that class.
class Meta(type):
def metamethod(meta, cls, self):
...
--
Steve
More information about the Tutor
mailing list