Anatomia della classe: il costruttore __init__

Introduzione alla programmazione orientata agli oggetti in Python

George Boorman

Curriculum Manager, DataCamp

Metodi e attributi

  • I metodi sono definizioni di funzione all'interno di una classe
  • self come primo argomento
  • Definisci gli attributi tramite assegnazione
  • Fare riferimento agli attributi nella classe tramite self.___
  • Chiamare troppi metodi potrebbe diventare insostenibile!
class MyClass:
    # function definition in class
    # first argument is self
    def my_method1(self, other_args...):
        # do things here

def my_method2(self, my_attr): # attribute created by assignment self.my_attr = my_attr ...
Introduzione alla programmazione orientata agli oggetti in Python

Costruttore

  • Aggiungi dati all'oggetto durante la creazione
  • Metodo costruttore __init__() viene chiamato ogni volta che viene creato un oggetto
    • Chiamato automaticamente a causa della sintassi __methodname__
class Customer:
    def __init__(self, name):
        # Create the .name attribute and set it to name parameter
        self.name = name
        print("The __init__ method was called")
Introduzione alla programmazione orientata agli oggetti in Python

Costruttore

# __init__ is implicitly called 
cust = Customer("Lara de Silva")   
print(cust.name)
The __init__ method was called
Lara de Silva
Introduzione alla programmazione orientata agli oggetti in Python

Attributi nei metodi

class MyClass:
    def my_method1(self, attr1):
        self.attr1 = attr1
        ...

    def my_method2(self, attr2):        
        self.attr2 = attr2
        ...

obj = MyClass() # attr1 created obj.my_method1(val1) # attr2 created obj.my_method2(val2)

Attributi nel costruttore

class MyClass:
    def __init__(self, attr1, attr2):
        self.attr1 = attr1
        self.attr2 = attr2
        ...

# All attributes are created obj = MyClass(val1, val2)
  • In generale dovremmo usare il costruttore
  • Gli attributi vengono creati quando l'oggetto viene creato
  • Codice più utilizzabile e manutenibile
Introduzione alla programmazione orientata agli oggetti in Python

Aggiungi argomenti

class Customer:
    # Add balance argument
    def __init__(self, name, balance): 

self.name = name # Add the balance attribute self.balance = balance print("The __init__ method was called")
Introduzione alla programmazione orientata agli oggetti in Python

Aggiungi parametri

# __init__ is called
cust = Customer("Lara de Silva", 1000)
print(cust.name)
print(cust.balance)
The __init__ method was called
Lara de Silva
1000
Introduzione alla programmazione orientata agli oggetti in Python

Argomenti predefiniti

class Customer:
    # Set a default value for balance
    def __init__(self, name, balance=0):
        self.name = name
        # Assign the new attribute
        self.balance = balance
        print("The __init__ method was called")
Introduzione alla programmazione orientata agli oggetti in Python

Argomenti predefiniti

# Don't specify the balance explicitly
cust = Customer("Lara de Silva")

print(cust.name) # The balance attribute is created anyway print(cust.balance)
The __init__ method was called
Lara de Silva
0
Introduzione alla programmazione orientata agli oggetti in Python

Best Practice:

1. Inizializza gli attributi in __init__()
Introduzione alla programmazione orientata agli oggetti in Python

Best Practice:

1. Inizializza gli attributi in __init__()
2. Denominazione

CamelCase per le classi, lower_snake_case per funzioni e attributi

Introduzione alla programmazione orientata agli oggetti in Python

Best Practice:

1. Inizializza gli attributi in __init__()
2. Denominazione

CamelCase per le classi, lower_snake_case per le funzioni e gli attributi

3. Mantieni self come self
class MyClass:
    # This works but isn't recommended
    def my_method(george, attr):
        george.attr = attr
Introduzione alla programmazione orientata agli oggetti in Python

Best Practice:

1. Inizializza gli attributi in __init__()
2. Denominazione

CamelCase per le classi, lower_snake_case per le funzioni e gli attributi

3. self è self
4. Usa le docstring
class MyClass:
    """This class does nothing"""
    pass
Introduzione alla programmazione orientata agli oggetti in Python

Passiamo alla pratica!

Introduzione alla programmazione orientata agli oggetti in Python

Preparing Video For Download...