Python for AIPython 3.10+ · Pydantic 2.12
0%
1
Curious builder0 XP earned · 300 to level 2
0 daysFinish a lesson to begin
Badge collection0 of 6 unlocked
33 small wins to finish your pathNext lesson

Classes: making your own kind of value

A dictionary accepts any key, so a typo quietly adds a new one. A class describes once what every ticket has, and each ticket made from it is an object.

Example
class Ticket:
    def __init__(self, ticket_id, customer, text):
        self.id = ticket_id
        self.customer = customer
        self.text = text

ticket = Ticket(1, "Asha", "I was charged twice for one order")
print(ticket.customer)
print(ticket.text)

class Ticket: starts the description. By convention class names start with a capital letter.

__init__, with two underscores each side, is the function Python runs when you write Ticket(...). Its first parameter, self, is the new object being made; the lines inside store the arguments on it as attributes, read later with a dot.

You never pass self yourself. Ticket(1, "Asha", ...) gives three arguments, and Python supplies the object as the first.

Many objects, one class

Example
first = Ticket(1, "Asha", "I was charged twice for one order")
second = Ticket(2, "Ben", "My parcel has not arrived")

second.customer = "Ben T."
print(first.customer, "/", second.customer)

Each object keeps its own attributes. Changing second leaves first alone.

An attribute that is not there

Example
ticket = Ticket(1, "Asha", "I was charged twice for one order")
print(ticket.priority)

A dictionary would have said KeyError; an object says AttributeError. Same idea: you asked for something that was never stored.

Printing an object

Example
ticket = Ticket(1, "Asha", "I was charged twice for one order")
print(ticket)

Python does not know which attributes matter, so it prints the class name and a memory address, which changes on every run. Lesson 21 fixes that.

Try it yourself
  • Add a fourth parameter, priority, to __init__ and store it.
  • Make a third ticket and print all three customers.
  • Call Ticket(1, "Asha") with one argument missing and read the error.

This is what real progress feels like.