Hi There!

I'm Dan Schlegel, an Associate Professor in the Computer Science Department at SUNY Oswego

Python’s Kinds of Functions

Functions

Methods are Functions Owned by a Class

Methods always take the instance as their first variable, but often this is done implicitly using the object instance followed by ‘.’ (dot), followed by the method name.

Static Methods

Static methods act like regular functions, but are logically grouped with the class and can be called with the class name or object variable, followed by ‘.’ (dot), followed by the function name.

An Aside: Class and Instance Variables

Class variables are those defined without using self (Pizza’s cheese variable, for instance), while instance variables use self (self.vegetable, for example). You must be very careful to keep these straight. Say we are interested in changing the value of the ‘cheese’ class variable. Upon creating two Pizza variables they have exactly what we expect for ‘cheese’:

Then, we set p2’s cheese to cheddar.

Why wasn’t Pizza’s class variable changed? Well, when we said p2.cheese = [‘cheddar’], we created a new *instance variable* called cheese which is owned by p2. When looking up the value of a variable, instance variables are checked before class variables, so that’s why we get the instance variable’s value back. And indeed, when we change the class variable:

The instance variable still takes precedence for p2:

This “creation of instance variables on the fly” is a thing which you can actually always do, and not only with variable names which are already used for class variables. It’s rather dangerous:

Class Methods

Class methods implicitly take the class as their first argument.

Class methods are usually used in two cases. First, as a factory method, building a class instance:

Static methods calling static methods (avoids need to hard-code class name):

Abstract Methods

An abstract method is a method defined in a base class, but that may not provide any implementation.

On the surface this seems a lot like Java’s abstract methods in interfaces or abstract classes, but see the next section.

If you’re interested in metaclasses, check out A Primer on Python Metaclasses.

Mixing Static, Class and Abstract Methods

Making Functions Attributes of Classes???

If you’ve done this, it’s not a good sign – you probably have made a mistake somewhere.

 

As Python 2.7 will only be supported until 2020, this page has been updated to reflect Python 3, with notes about Python 2.7.

Some of the contents of this page are adapted from a post on Julien Danjou’s blog. This page is therefore licensed under the Creative Commons Attribution-ShareAlike 3.0 Unported License.