I’m teaching myself Python and I was translating some sample code into this
class Student(object):
def __init__( self, name, a,b,c ):
self.name = name
self.a = a
self.b = b
self.c = c
def average(self):
return ( a+b+c ) / 3.0
Which is pretty much my intended class definition.
Later in the main method I create an instance and call it a:
if __name__ == "__main__" :
a = Student( "Oscar", 10, 10, 10 )
That’s how I find out that the variable a declared in main is available to the method average and to make that method work, I have to type self.a + self.b + self.c instead.
What’s the rationale for this?
Barenames (like
a,b,c) are always scoped as local or global (save for nested functions, which are nowhere around in your code). The rationale is that adding further scopes would needlessly make things more complicated — e.g, if in yourself.a = athe barenameacould be scoped to mean what you appear to want (equivalent toself.a) then the assignment itself would be meaningless (assigning a name to itself), so you’d need further complicated rules.Just using qualified names (like
self.a) when you want something different than barenames’ simple, straightforward, and optimized behavior, is by far the simplest approach — perfectly workable, no complicated rules whatsoever, and allows the compiler to optimize things effectively (since e.g. a barename’s scope is always lexically determined, not dependent on dynamically varying characteristics of the environment). So, besides perhaps nostalgia for other language with more complicated scoping rules, there’s really no rationale for complicating the semantics of barenames.