Module lessons (1/4)
Classes and instances
A class is a blueprint for creating objects that have data (attributes) and behavior (methods). An instance is a concrete object created from the class.
Minimal syntax
class Cane:
def __init__(self, nome, eta):
self.nome = nome
self.eta = eta
def abbaia(self):
return f"{self.nome} dice WOOF!"
# creazione di istanze
fido = Cane("Fido", 3)
luna = Cane("Luna", 5)
fido.nome # 'Fido'
fido.abbaia() # 'Fido dice WOOF!'__init__: the "constructor"
The __init__ method is called automatically when you create an
instance (Cane("Fido", 3)). It is used to initialize the attributes.
Technically it is not a constructor (the object has already been created by
__new__), but it is the place where you set the initial state.
self: the first parameter
self is the reference to the instance the method was called on. It is a
convention (not a keyword) and is always the first parameter of instance
methods.
fido.abbaia()
# equivalente a Cane.abbaia(fido)
# Python passa fido come self automaticamenteInstance vs class attributes
class Cane:
specie = "Canis familiaris" # attributo di CLASSE (condiviso)
def __init__(self, nome):
self.nome = nome # attributo di ISTANZA (per ognuno)
fido = Cane("Fido")
luna = Cane("Luna")
fido.nome # 'Fido' (istanza)
luna.nome # 'Luna' (istanza)
fido.specie # 'Canis familiaris' (cercato sulla classe)
Cane.specie # 'Canis familiaris'Multiple methods and state
class Contatore:
def __init__(self, inizio=0):
self.valore = inizio
def incrementa(self, di=1):
self.valore += di
def reset(self):
self.valore = 0
c = Contatore()
c.incrementa()
c.incrementa(di=5)
c.valore # 6
c.reset()
c.valore # 0Your turn
Define a class `Point` with __init__(self, x, y) that stores the attributes. Add a method `distance_from_origin` that returns the square root of x^2 + y^2. Create `p = Point(3, 4)` and evaluate `p.distance_from_origin()`.
Show hint
math.sqrt(self.x ** 2 + self.y ** 2)
Solution available after 3 attempts
Review exercise
Define `BankAccount` with __init__(self, balance=0) and methods `deposit(amount)`, `withdraw(amount)` that modify self.balance. Create `a = BankAccount(100)`, deposit 50, withdraw 30. Evaluate `a.balance`.
Show hint
self.balance += amount in deposit.
Solution available after 3 attempts
Additional challenge
Define a class `Rectangle` with a constructor `__init__(self, width, height)` to set width and height, and a method `area(self)` that returns the product of width and height. Instantiate a rectangle with width `4` and height `5` storing it in `rect`, and evaluate `rect.area()`.
Show hint
Remember to use self to access attributes inside area(self).
Solution available after 3 attempts