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.
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
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
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
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.
- 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.