Classes

  • A class is a useful object that is essentially a variable type (Python object) that you can define yourself.
  • C lets you define structs, which is a single object that can contain many other named variables. A class extends this concept in several ways, most obviously a class can contain both variables (properties) and functions (methods).
  • In general a class will embody some object and the data + functions that make sense to bundle together. Let's see some very simple syntax examples before moving on to the scripts directory where more complete examples are given.

In [7]:
# Define a class with the class keyword
class A:
    """Docstrings work here too"""
    x = 5   # defining properties of the class
    y = 7

print(A)
print(A.x, A.y)   # Access properties with `.` as with other Python objects
A.x = 1           # Can change the class properties from outside the definition
print(A.x, A.y)


<class '__main__.A'>
5 7
1 7
  • This seems useless as you can only have one copy of the class and one set of values for properties.
  • What we want are different instances of the class that can contain different values. These can then be assigned to variables.

In [3]:
class B:
    x = 3  # Evaluated once during the definition (similar to functions)
    y = [] # These will be initially the same for all instances
    
    def __init__(self, z):
        """This function is special. It's run when the instance of the class is created and
        is useful to set up some initial state of the class. The argument 'self' isn't a
        keyword but is the convention, it is basically the instance being passed into the
        class."""
        self.z = z   # Can be different for each instance
    
    def z_squared(self):
        return self.z**2

# Instances are created in a similar way to functions and use the arguments from the 
# __init__ function if it exists.
f = B(3)   # Note there is only the z argument because the 'self' is automatically passed in
g = B(4)
print(f.x, g.x)   # Same values
B.x = 5
print(f.x, g.x)   # Both changed

print(f.y, g.y)   # Same values
B.y.append("Hello")
print(f.y, g.y)   # Both changed

print(f.z_squared(), g.z_squared())    # Call class methods in a usual way

# The `self` argument becomes more obvious when you realise that these are
# equivalent statements
print(f.z_squared(), B.z_squared(f))
print(g.z_squared(), B.z_squared(g))


3 3
5 5
[] []
['Hello'] ['Hello']
9 16
9 9
16 16
  • Now move on to the scripts directory to see some other class features and some awesome Python examples using the Python standard library and some of its extensive third party libraries for scientists.