bhylu.com

Advertisements

Classes/Objects

A class defines a type of object; calling it usually creates an instance. Different instances can keep different values while using the same methods.

Understand the idea

Methods receive the instance through the conventional self parameter. Attributes can be set on an instance, but an explicit initializer makes required state clearer. Avoid confusing attributes on the class with per-instance attributes, especially when the value is mutable. A shared class-level list can unexpectedly collect values from every instance.

Where to try it

Open this example with Try in playground. The code loads as editable text and does not run until you select Run. The first run downloads Python. Each run starts fresh; temporary files created by a script are not files on your PC.

A worked example

Python

class Workshop:
    def __init__(self, title):
        self.title = title

first = Workshop("Python")
second = Workshop("SQL")
print(first.title, second.title)

Read the result

The output is Python SQL because each instance has its own title.

Try one change

Give each workshop its own attendees list and prove that adding to one leaves the other unchanged.