Classes
class, __init__, self and methods.
A class describes a new data type: what data an object has (attributes) and what it can do (methods). An object created from a class is called an instance.
class Lamp:
def __init__(self, room, on=False):
self.room = room
self.on = on
def toggle(self):
self.on = not self.on
return self.on
lamp = Lamp("kitchen")
lamp.toggle()
print(lamp.room, lamp.on) # kitchen True
__init__ is called when an object is created and fills in its attributes. The first parameter of every method is self, the object itself. When you call lamp.toggle(), Python passes lamp as self for you, so only the other arguments go in the brackets.
Each instance has its own data: two lamps in different rooms are switched on and off independently. An attribute assigned through self inside __init__ lives as long as the object does.
Why have classes when there are dictionaries? A class keeps data and the rules for working with it in one place. If, for example, the balance of an account changes only through a deposit method, the check "the amount must be positive" only needs to be written once, inside that method.
Attributes that start with a single underscore (self._balance) are by convention internal: code outside the class does not touch them. Python does not forbid it, but this way a reader of the code sees which attributes belong to the public interface.
Practice
What self is
What is self in a method of a class?
- The object whose method is called
- A keyword for creating a class
- A copy of the class
- A global variable of the module
A counter
What does the program print?
class Counter: def __init__(self): self.value = 0 def add(self): self.value += 1 c = Counter() c.add() c.add() print(c.value)A bank account
Write a class Account: the constructor takes owner and balance with a default of 0, and the method deposit(amount) increases the balance and returns the new value. If amount is not greater than zero, deposit raises ValueError.