Skip to content

Classes

A more generalized approach

Each of these samples has the same kind of information attached to it, so we can describe what a sample in general looks like: We can summarize these common features as: “Every sample has an inventory number and a collector”.

This abstraction is called a class. The “variables” that each object of the same class has are called attributes. In our case these are id and collector.

Kroki

Let us see how to write this down in Python, step-by-step:

# Here is the most minimal class
class Sample:
    pass  # Tell Python that this is all

# Create an instance and set the attributes
my_sample = Sample()
my_sample.id = "22-A-15"
my_sample.collector = "Darwin"

print("Object:", my_sample)
print("ID:", my_sample.id)
print("Collected by:", my_sample.collector)

Note how the output of printing an object directly is pretty awkward. We will learn how to improve that later.

There is one further important insight: Classes are data types. Try:

my_sample = Sample()
type(my_sample)
This means that you can use any object as a value for variables or put them into a function as values for parameters.