Python from zero: a class is the object
A class groups fields and a method. Item stores a drink and a price in cents. label prints latte $4.50.
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.
A drink is a name and a price. A class is the object that holds both. __init__ fills the fields when you call Item(...). A method takes self, which is the object you called it on. label is the line you would put on a cup.
The instance holds the fields#
class Item defines a way to build objects. Item("latte", 450) calls __init__, and self is the new instance. Assigning self.name stores an attribute on that instance, not on the class. label receives the same instance as self when you write latte.label(). The method builds a string and returns it. The instance is unchanged. Two calls to Item make two objects. They do not share name or cents.
- namestrlatte
- centsint450
- labelstrlatte $4.50
class Item:
def __init__(self, name, cents):
self.name = name
self.cents = cents
def label(self):
return f"{self.name} ${self.cents // 100}.{self.cents % 100:02d}"
latte = Item("latte", 450)
print(latte.label())
latte $4.50
self is the object#
Item("latte", 450) makes an object and calls __init__ with that object as self. self.name = name stores the argument on the object. After that line, latte.name is "latte" and latte.cents is 450.
label also takes self. latte.label() passes latte in as self for you. You do not write latte.label(latte). Inside the method, // and % turn the cents into dollars and leftover cents. :02d keeps two digits after the dot. Forgetting that the cents are an int, and adding them to the name with +, raises TypeError, the same error as lesson 1.
The fields belong to this drink#
A second Item("tea", 250) has its own name and cents. Changing latte.cents does not change the tea. self is how a method knows which object it was called on. The next lesson is the tip about two names that point at one list.
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.