Fondamenti di programmazione orientata agli oggetti

Programmazione a oggetti intermedia in Python

Jake Roach

Data Engineer

Definire una classe

class Person:
  def __init__(self, name, age):
    self.name = name
    self.age = age
    self.height = 0

# This invokes a call to __init__
john = Person("John Casey", 38)
  • Definisci una classe con la parola chiave class
  • __init__ è il costruttore, chiamato quando si crea un nuovo oggetto della classe
  • self si riferisce all'istanza corrente della classe
Programmazione a oggetti intermedia in Python

Attributi di istanza

class Person:
  def __init__(self, name, age):
    self.name = name
    self.age = age
# Create an instance of Person
sarah = Person("Sarah Walker", 31)
sarah.age  # Retrieve the age instance attribute
  • Associate a un oggetto della classe
  • Si impostano e leggono con la sintassi self.<attribute-name>
  • Si accedono tramite <object-name>.<attribute-name>
Programmazione a oggetti intermedia in Python

Attributi di classe

  • Legati alla classe stessa
  • Si leggono senza un oggetto della classe
  • Conservano dati uguali per tutti gli oggetti della classe
class Person:
  residence = "Planet Earth"
  ...
# Accessed without an instance
print(Person.residence)
Planet Earth
Programmazione a oggetti intermedia in Python

Metodi di istanza

class Person:
  ...
  def introduce(self):
      print(f"Hello, my name is {self.name}")
chuck = Person("Chuck", 32)
chuck.introduce()  # Called on a Person object

$$

  • Richiedono un oggetto della classe per essere chiamati
  • Hanno self come primo parametro
Programmazione a oggetti intermedia in Python

Metodi di classe

class Person:
  @classmethod
  def wake_up(cls):
      print("Time to start your day!")
# Calling a class method
Person.wake_up()

$$

  • Decorati con @classmethod
  • Non richiedono un oggetto della classe per essere chiamati
Programmazione a oggetti intermedia in Python

Ereditarietà

L'ereditarietà permette di riutilizzare codice tra classi

  • La classe figlia (Employee) eredita tutta la funzionalità della classe genitore (Person)
  • Relazione «is-a»
  • Può aggiungere funzionalità extra
    • Attributi
    • Metodi
class Person:
  def __init__(self, name, age):
    self.name
    self.age = age

  def introduce(self):
      print(f"Hello, my name is {self.name}")
class Employee(Person):
  def __init__(self, name, age, title):
    Person.__init__(self, name, age)
    self.title = title

  def change_position(self, new_title):
      self.title = new_title
Programmazione a oggetti intermedia in Python

Ereditarietà

lester = Employee("Lester", 26, "Technician")
lester.introduce()  # Inherited from Person
print(lester.title)
Hello, my name is Lester
Technician
lester.change_position("Cashier")
print(lester.title)
Cashier
Programmazione a oggetti intermedia in Python

super()

class Employee(Person):
  def __init__(self, name, age, title):
    # Uses name of the parent class
    Person.__init__(self, name, age)

    self.title = title
  ...
  • Nome della classe, __init__()

Usare super()

class Employee(Person):
  def __init__(self, name, age, title):
    # super(), instead of class name
    super().__init__(name, age)

    self.title = title
  ...
  • super(), __init__()
  • Non serve passare self
Programmazione a oggetti intermedia in Python

Override

La classe figlia implementa in modo nuovo un metodo ereditato dal genitore

class Employee(Person):
  ...
  def introduce(self):
      print(f"""My name is {self.name},
        I am a {self.title}""")
lester = Employee("Lester", 26, "Technician")
lester.introduce()
My name is Lester, I am a Technician
Programmazione a oggetti intermedia in Python

Overload

class Person:
  def __init__(self, name):
      self.name = name

  def __eq__(self, other):
      return self.name == other.name

$$

  • Personalizza il comportamento degli operatori Python per una classe
  • __eq__() sovraccarica ==

$$

$$

$$

$$

# Compare two Person objects
chuck = Person("Charles Carmichael")
charles = Person("Charles Carmichael")
print(chuck == charles)
True
Programmazione a oggetti intermedia in Python

Esercitiamoci!

Programmazione a oggetti intermedia in Python

Preparing Video For Download...