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.
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
def summary(self):
return f"#{self.id} {self.customer}: {self.category}"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
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.
- Add a method
is_urgent(self)that returnsTruefor billing tickets. - Call
ticket.summary()beforeticket.categorise(). - Add an
"account"branch for passwords, and a third ticket that uses it.
Every expert started right here.