Python from zero: a method uses self
A method changes the object through self. A bill starts at 0 cents, add puts a latte on it, and the program prints 450.
Zoe is one of GoByte's characters. This post was drafted by AI agents in Zoe's voice, then fact checked, run and edited by the GoByte team.
Lesson 2 called a method that only read the fields. A method can also change them. self.cents is the field on the bill. Assigning to it changes that object, and the name in the script sees the new total.
self is the instance the call was made on#
A function defined on a class is a method once you call it on an instance. bill.add(450) is roughly Bill.add(bill, 450). The first parameter is named self by convention, and it is the instance, so self.cents = self.cents + cents reads and writes that object's attribute. Forgetting self in the definition makes the call fail, because the instance still arrives as the first argument and then has nowhere to land. The attribute starts at 0 because __init__ set it. 0 is an empty bill, not a missing one.
- start0
- add(450)450
class Bill:
def __init__(self):
self.cents = 0
def add(self, cents):
self.cents = self.cents + cents
bill = Bill()
bill.add(450)
print(bill.cents)
450
The field starts at a real zero#
__init__ sets self.cents = 0. A new bill has nothing on it, and 0 says that. add reads self.cents, adds the cents you passed, and stores the sum back. bill.add(450) is one latte. The print is 450, the cents you would charge before a tip. A second bill.add(450) would print 900.
Forgetting self is the usual slip. def add(cents): is a function, not a method, and bill.add(450) then fails because Python still tries to pass bill in. cents = self.cents + cents without the self.cents = makes a local name and leaves the field at 0. The object only changes when you assign to self.cents.
One bill, one total#
other = Bill() has a different cents. bill.add(450) does not move other. The method always changes the object before the dot. The next lesson uses a precise decimal type when the price arrives as 4.10, because a binary float cannot hold that exactly.
Your product here? Partner with us
Back to topDiscussion
No comments yet. Signed in GoByte members with a verified e-mail can join. Community guidelines
Reading is open to everyone. Commenting and voting need a GoByte account with a verified e-mail.