Home > Articles > Open Source > Python

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

4.13 Recapitulation of the Scope of Names

It is important to understand the scopes of names used in methods. There are unqualified names—in other words, variable names—and qualified names of the form object.attribute.

Unqualified names in methods are the same as unqualified names in other functions. They name parameters and local variables of the method, variables in the surrounding module, or built-in variables of the Python system. They never refer to attributes of the instance of the class or of the class itself. This is unlike many other object-oriented languages, so if you know them, you have to be careful using Python.

Your methods must get at attributes of the instance or the class using qualified names. Your method's first parameter will point to the instance your method is being called for. The custom is to call this parameter self, to remind you of its meaning. You get at all attributes of the instance using this parameter; that is, by self.name. When name isn't found in the attributes of the instance, Python searches the class of the instance and its superclasses using a depth-first, left-to-right search. If it finds a function in a class with the name you are searching for, Python gives you a bound method object that allows you to call the method for the current object. You can use this to make up calls or down calls, wherever the method is found in the class hierarchy. It's the same as calling the method from outside the object.

You can also look up functions directly in classes, which gives you an unbound method object. To call it, you have to provide it an instance as its first parameter. You use this to make explicit up calls to superclass implementations of overridden methods. A method uses this to call the method it is overriding.

  • + Share This
  • 🔖 Save To Your Account