Programmazione orientata agli oggetti (OOP) in Python

Programmazione orientata agli oggetti (OOP) in Python Programmazione orientata agli oggetti (OOP) in Python.md

Programmazione orientata agli oggetti (OOP) in Python

Versione italiana

La programmazione orientata agli oggetti (OOP) è un paradigma di programmazione che organizza il codice in "oggetti", che sono istanze di "classi". Questo approccio rende il codice più modulare, riutilizzabile e facile da mantenere.


Introduzione alla OOP

  1. Cos'è la OOP?

    • La OOP si basa su quattro principi fondamentali:
      1. Incapsulamento: nascondere i dettagli interni di un oggetto e esporre solo un'interfaccia.
      2. Ereditarietà: creare nuove classi basate su classi esistenti.
      3. Polimorfismo: usare un'interfaccia comune per operare su oggetti di tipi diversi.
      4. Astrazione: rappresentare solo le caratteristiche essenziali di un oggetto.
  2. Vantaggi della OOP:

    • Riutilizzo del codice: le classi possono essere riutilizzate in diversi progetti.
    • Modularità: il codice è organizzato in unità logiche (classi e oggetti).
    • Manutenibilità: è più facile modificare e estendere il codice.

Classi e oggetti

  1. Definizione di una classe (class):

    • Una classe è un modello o un "blueprint" per creare oggetti.
    • Si definisce usando la parola chiave class.
    • Esempio:
      class Persona: pass
  2. Creazione di oggetti:

    • Un oggetto è un'istanza di una classe.
    • Si crea chiamando la classe come se fosse una funzione.
    • Esempio:
      persona1 = Persona() # Creazione di un oggetto

Attributi e metodi

  1. Attributi:

    • Sono variabili associate a una classe o a un oggetto.
    • Possono essere di classe (condivisi da tutte le istanze) o di istanza (specifici per ogni oggetto).
    • Esempio:
      class Persona: # Attributo di classe specie = "Homo Sapiens" def __init__(self, nome, eta): # Attributi di istanza self.nome = nome self.eta = eta persona1 = Persona("Mario", 30) print(persona1.nome) # Output: Mario print(persona1.specie) # Output: Homo Sapiens
  2. Metodi:

    • Sono funzioni definite all'interno di una classe.
    • Operano sugli attributi dell'oggetto.
    • Esempio:
      class Persona: def __init__(self, nome, eta): self.nome = nome self.eta = eta def saluta(self): print(f"Ciao, mi chiamo {self.nome}!") persona1 = Persona("Mario", 30) persona1.saluta() # Output: Ciao, mi chiamo Mario!

Ereditarietà e polimorfismo

  1. Ereditarietà:

    • Una classe può ereditare attributi e metodi da un'altra classe (chiamata classe genitore o superclasse).
    • Esempio:
      class Animale: def __init__(self, nome): self.nome = nome def parla(self): print("...") class Cane(Animale): # Cane eredita da Animale def parla(self): print("Bau!") cane1 = Cane("Fido") cane1.parla() # Output: Bau!
  2. Polimorfismo:

    • Consente a oggetti di classi diverse di rispondere allo stesso metodo in modo diverso.
    • Esempio:
      class Gatto(Animale): def parla(self): print("Miao!") animali = [Cane("Fido"), Gatto("Whiskers")] for animale in animali: animale.parla() # Output: Bau! Miao!

Metodi speciali

  1. Metodi speciali:

    • Sono metodi predefiniti che iniziano e finiscono con doppi underscore (__).
    • Vengono chiamati automaticamente in situazioni specifiche.
  2. Esempi di metodi speciali:

    • __init__: metodo costruttore, chiamato quando si crea un oggetto.
    • __str__: definisce la rappresentazione in stringa dell'oggetto (usato da print).
    • __repr__: definisce una rappresentazione formale dell'oggetto (usato da repr).
    • __len__: definisce il comportamento di len().

    Esempio:

    class Persona: def __init__(self, nome, eta): self.nome = nome self.eta = eta def __str__(self): return f"{self.nome} ({self.eta} anni)" def __repr__(self): return f"Persona('{self.nome}', {self.eta})" persona1 = Persona("Mario", 30) print(persona1) # Output: Mario (30 anni) print(repr(persona1)) # Output: Persona('Mario', 30)

Proprietà (@property)

  1. Proprietà:

    • Le proprietà permettono di definire metodi che si comportano come attributi.
    • Si usano i decoratori @property, @nome.setter e @nome.deleter.
  2. Esempio:

    class Persona: def __init__(self, nome, eta): self.nome = nome self._eta = eta # Attributo "privato" @property def eta(self): return self._eta @eta.setter def eta(self, valore): if valore < 0: raise ValueError("L'età non può essere negativa!") self._eta = valore persona1 = Persona("Mario", 30) print(persona1.eta) # Output: 30 persona1.eta = 25 # Modifica l'età print(persona1.eta) # Output: 25

    English version

    Object Oriented Programming (OOP) in Python

Object Oriented Programming (OOP) is a programming paradigm that organizes code into "objects", which are instances of "classes". This approach makes code more modular, reusable, and easier to maintain. Here is a detailed explanation of the concepts you mentioned:


Introduction to OOP

  1. What is OOP?
  • OOP is based on four fundamental principles:
  1. Encapsulation: Hiding the internal details of an object and exposing only an interface.

  2. Inheritance: Creating new classes based on existing classes.

  3. Polymorphism: Using a common interface to operate on objects of different types.

  4. Abstraction: Representing only the essential characteristics of an object.

  5. Advantages of OOP:

  • Code reuse: classes can be reused in different projects.
  • Modularity: code is organized into logical units (classes and objects).
  • Maintainability: code is easier to modify and extend.

Classes and objects

  1. Definition of a class (class):
  • A class is a template or a "blueprint" for creating objects.
  • It is defined using the keyword class.
  • Example:
class Person: pass
  1. Creation of objects:
  • An object is an instance of a class.
  • It is created by calling the class as if it were a function.
  • Example:
person1 = Person() # Creating an object

Attributes and methods

  1. Attributes:
  • They are variables associated with a class or an object.
  • They can be class-based (shared by all instances) or instance-based (specific to each object).
  • Example:
class Person: # Class attribute species = "Homo Sapiens" def __init__(self, name, age): # Instance attributes self.name = name self.age = age person1 = Person("Mario", 30) print(person1.name) # Output: Mario print(person1.species) # Output: Homo Sapiens
  1. Methods:
  • They are functions defined within a class.
  • They operate on the object's attributes.
  • Example:
class Person: def __init__(self, name, age): self.name = name self.age = age def greet(self): print(f"Hello, my name is {self.name}!") person1 = Person("Mario", 30) person1.greet() # Output: Hello, my name is Mario!

Inheritance and Polymorphism

  1. Inheritance:
  • A class can inherit attributes and methods from another class (called parent class or superclass).
  • Example:
class Animal: def __init__(self, name): self.name = name def speak(self): print("...") class Dog(Animal): # Dog inherits from Animal def speak(self): print("Woof!") dog1 = Dog("Fido") dog1.speak() # Output: Woof!
  1. Polymorphism:
  • Allows objects of different classes to respond differently to the same method.
  • Example:
class Cat(Animal): def speak(self): print("Meow!") animals = [Dog("Fido"), Cat("Whiskers")] for animal in animals: animal.speak() # Output: Woof! Meow!

Special Methods

  1. Special Methods:
  • These are predefined methods that start and end with double underscores (__).
  • They are called automatically in specific situations.
  1. Examples of Special Methods:
  • __init__: Constructor method, called when an object is created.
  • __str__: Defines the string representation of the object (used by print).
  • __repr__: Defines a formal representation of the object (used by repr).
  • __len__: Defines the behavior of len().

Example:

class Person: def __init__(self, name, age): self.name = name self.age = age def __str__(self): return f"{self.name} ({self.age} years)" def __repr__(self): return f"Person('{self.name}', {self.age})" person1 = Person("Mario", 30) print(person1) # Output: Mario (30 years) print(repr(person1)) # Output: Person('Mario', 30)

Properties (@property)

  1. Properties:
  • Properties allow you to define methods that behave like attributes.
  • Use the decorators @property, @name.setter and @name.deleter.
  1. Example:
class Person: def __init__(self, name, age): self.name = name self._age = age # "Private" attribute @property def age(self): return self._age @age.setter def age(self, value): if value < 0: raise ValueError("Age cannot be negative!") self._age = value person1 = Person("Mario", 30) print(person1.age) # Output: 30 person1.age = 25 # Change age print(person1.age) # Output: 25

Commenti