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

Methods: functions that belong to an object

The Ticket class from lesson 19 holds data but does nothing. A method is a function written inside the class, and it works on the object it is called on.

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

    def categorise(self):
        text = self.text.lower()
        if "charged" in text or "refund" in text:
            self.category = "billing"
        elif "parcel" in text or "arrived" in text:
            self.category = "shipping"
        else:
            self.category = "other"

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

__init__ now starts every ticket with category set to None. categorise is a method: def inside the class, with self first.

ticket.categorise() passes ticket in as self, so self.text is this ticket's text and setting self.category changes this ticket. It is the categorise function from lesson 11, now keeping its answer on the object.

A method that returns

Exampleadded inside class Ticket, below categorise
    def summary(self):
        return f"#{self.id} {self.customer}: {self.category}"
Example
tickets = [
    Ticket(1, "Asha", "I was charged twice for one order"),
    Ticket(2, "Ben", "My parcel has not arrived"),
]
for ticket in tickets:
    ticket.categorise()
    print(ticket.summary())

A list of objects works like the list of dictionaries in lesson 9, and each one knows how to sort and describe itself.

Forgetting self

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

    def shout():
        return "TICKET"

Ticket("refund").shout()

Python always passes the object as the first argument to a method. A method written without a parameter for it receives one argument it has no room for.

Try it yourself
  • Add a method is_urgent(self) that returns True for billing tickets.
  • Call ticket.summary() before ticket.categorise().
  • Add an "account" branch for passwords, and a third ticket that uses it.

Every expert started right here.