Anatomia della classe: attributi e metodi

Introduzione alla programmazione orientata agli oggetti in Python

George Boorman

Curriculum Manager, DataCamp

Una classe Customer

class Customer:

# Code for class goes here
pass
  • class <name>: avvia una definizione di classe
  • Il codice all'interno di class è rientrato
  • Usa pass per creare una classe "vuota"
c_one = Customer()
c_two = Customer()
  • Usa ClassName() per creare un oggetto della classe ClassName
Introduzione alla programmazione orientata agli oggetti in Python

Aggiungi metodi a una classe

class Customer:  

def identify(self, name): print("I am Customer " + name)
  • Definizione del metodo = definizione di funzione all'interno della classe
  • Usa self come primo argomento nella definizione del metodo
cust = Customer()
cust.identify("Laura")
I am Customer Laura
  • Ignora self quando chiami un metodo su un oggetto
Introduzione alla programmazione orientata agli oggetti in Python
class Customer:  
    def identify(self, name):
        print("I am Customer " + name)

cust = Customer()
cust.identify("Laura")

Che cos'è il sé?

  • Le classi sono modelli
  • self dovrebbe essere il primo argomento di qualsiasi metodo
  • self è un segnaposto per un oggetto{{3}} (non ancora creato)
  • cust.identify("Laura") sarà interpretato come Customer.identify(cust, "Laura")
Introduzione alla programmazione orientata agli oggetti in Python

Abbiamo bisogno di attributi

  • OOP raggruppa i dati con i metodi che operano sui dati
    • Il nome di Customer's' dovrebbe essere un attributo

$$\text{\Large{Gli attributi vengono creati tramite assegnazione (=) nei metodi}}$$

Introduzione alla programmazione orientata agli oggetti in Python

Aggiungi un attributo alla classe

class Customer:  
    # Set the name attribute of an object to new_name
    def set_name(self, new_name):

# Create an attribute by assigning a value # Will create .name when set_name is called self.name = new_name
# Create an object # .name doesn't exist here yet cust = Customer()
# .name is created and set to "Lara de Silva" cust.set_name("Lara de Silva")
print(cust.name)
Lara de Silva
Introduzione alla programmazione orientata agli oggetti in Python

Vecchia versione

class Customer:  



    # Using a parameter
    def identify(self, name):
        print("I am Customer" + name)
cust = Customer()

cust.identify("Eris Odoro") 
I am Customer Eris Odoro 

Nuova versione

class Customer:  
   def set_name(self, new_name):
       self.name = new_name

# Using .name from the object it*self* def identify(self): print("I am Customer" + self.name)
cust = Customer()
cust.set_name("Rashid Volkov")
cust.identify()
I am Customer Rashid Volkov
Introduzione alla programmazione orientata agli oggetti in Python

Passiamo alla pratica!

Introduzione alla programmazione orientata agli oggetti in Python

Preparing Video For Download...