As a true object-oriented language, Python is a great place tostart learning about OO programming. In this first segment of a two-partarticle, take your Python skills to the next level with a discussion ofclasses and class instances. Practical (and not-so-practical) examplesincluded.
You'll have noticed, in the examples above, a curious little thingummy called "self". And you're probably wondering what exactly it has to do with anything.
The "self" variable has a lot to do with the way class methods work in Python. When a class method is called, it requires to be passed a reference to the instance that is calling it. This reference is passed as the first argument to the method, and is represented by the "self" variable.
class veryBigSnake:
# some useful methods
def set_snake_name(self, name):
self.name = name
An example of this can be seen in the set_snake_name()
function above. When an instance of the class calls this method, a reference to the instance is automatically passed to the method, together with the additional "name" parameter. This reference is then used to update the "name" variable belonging to that specific instance of the class.
Note that when you call a class method from an instance, you
do not need to explicitly pass this reference to the method - Python takes care of this for you automatically.
In this case, I'm calling the class method directly (not via
an instance), but passing it a reference to the instance in the method call - which makes this snippet equivalent to the one above it.