Python from zero: a method is enough
A function can call label on any object that has label. Item has that method. show 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.
show needs one method. It does not need the class name. If the object has label, the call works. That is the object-oriented deal in Python: the method is the contract, and the class is how you group the data the method uses. A discount line with its own label can use the same function.
Any object with the method will do#
show does not name Item. It calls obj.label() and prints the result. That is a protocol: the caller requires a method, and the object either has it or the call raises AttributeError. There is no interface declaration to implement. A second class with a label method can be passed in, and show stays as it is. The cost of that freedom is that the mistake appears when the line runs, not when the file is compiled.
- Itemlabel()latte $4.50
- no labelmissingAttributeError
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}"
def show(obj):
print(obj.label())
show(Item("latte", 450))
latte $4.50
The dot finds the method#
show receives the latte as obj and calls obj.label(). Python looks up label on the object. Item defined it, so the call returns "latte $4.50" and print writes that line. A second class with a label method of its own can be passed to the same show. show does not change.
If the object has no label, the call raises AttributeError and names the missing attribute. That is the check. Catch it only when a missing label is a normal case. Otherwise let it surface, and add the method.
Keep the method small enough to share#
label uses the fields and returns text. It does not print, and it does not ask what the caller is. show is the one that prints. Splitting them means you can use label on a receipt, in a test, or in another function without dragging print along. Pass the object. Let the method do one job.
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.