A Method to the Madness¶
For now let us focus on how to extend our new class with a bit of functionality.
To do so we will define something that reminds us of functions.
In the context of OOP this is called a method.
Usually, a method needs to refer to a particular object which it operates on.
In Python this object is passed in as the first parameter, called
This parameter will be filled in automatically by Python if you call the method via the
.-operator, hence you do not need to to pass
self into the method even though it is part of the list of parameters in the method signature.
Let’s take a look at another example:
class Sample: # !!! Mind the indentation !!! def print_me(self): print("I am", self, "of type", type(self)) # Create some new Sample instances my_sample = Sample() my_other_sample = Sample() print("--- Printing my_sample ---") my_sample.print_me() # Note that Python fills in the "self" automatically # In the above line, "self" will be the "my_sample"-object print("--- Printing my_other_sample ---") my_other_sample.print_me() # Here, "self" will be "my_other_sample"
The output of
print_me() is not very nice or helpful at all.
If you want to pretty-print an object you will have to implement a special method called
More on that later…
It would be really nice if we could set the instance attributes directly when creating an instance, wouldn’t it? A special method, called a constructor, can help us with that:
# Declare to python that there is a new class class Sample: # Tell python how to construct an object of that class def __init__(self, identifier, collector): self.identifier = identifier self.collector = collector # Let's try that out some_sample = Sample(identifier="0123", collector="Darwin") # ← Constructor call # You still can use the .-operator to access attributes and methods print(some_sample.identifier) # Hey we can also have multiple samples in a list samples = [ Sample(identifier="0123", collector="Darwin"), Sample(identifier="0124", collector="Mendel"), Sample(identifier="0120a", collector="Darwin"), Sample(identifier="0120b", collector="Irwin"), ] # Who collected the first sample again? print(samples.collector)
Now we have the most essential components to build ourselves a first useful version of a
class Sample: # This is the constructor def __init__(self, identifier, collector): self.identifier = identifier self.collector = collector # This will help us with printing the instances in a nice fashion def __str__(self): return "Sample: " + self.identifier + ", collected by " + self.collector # Lets try that out sample = Sample(identifier="0123", collector="Darwin") # This is possible since we implemented the __str__-method print(sample)
- The method signature is
- It must return a string.
- The method will be called by
print(…)to figure out how to display an object on the command line.