Object-Oriented Programming · 20 min

Create objects and manage instance state

Initialize an instance, change its state, and give it a readable representation.

Jump to the automation lab

Calling a class creates an instance and runs __init__ to initialize it. Store each object’s own values on self. A method receives that instance as its first argument when you call it through the object.

__str__ defines the user-facing text produced by str(instance) or print(instance). A representation can use state, but it should leave the object unchanged.

Create two objects when testing instance behavior. A state change on one should leave a separate instance alone.

Follow the example

The initializer stores a name and a count for this object.

Run the example and practice

Add reset(), which changes this counter’s total to zero. Print the counter after adding three, then print it again after resetting.

Target output

visits: 5
visits: 0
Show a hint

Assign 0 to self.total inside reset. Keep the existing initializer and add method.

Output

Ready

Run your code to see the output here.

Check output also tests your code with additional cases.

The first run downloads Python. Code runs in your browser. Progress and drafts are stored on this device.

Show one solution
class Counter:
    def __init__(self, name, total=0):
        self.name = name
        self.total = total

    def add(self, amount=1):
        self.total += amount

    def reset(self):
        self.total = 0

    def __str__(self):
        return f"{self.name}: {self.total}"

counter = Counter("visits", 2)
counter.add(3)
print(counter)
counter.reset()
print(counter)

Automation lab

Track supplies one bin at a time

Give each stock bin its own count. Update the first bin and confirm the other keeps its original value.

Output

Ready

Run the example to see the output here.

Add a method that checks whether this bin has fewer than 10 units.

Further reading in Automate the Boring Stuff with Python by Al Sweigart