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
-
Cos'è la OOP?
- La OOP si basa su quattro principi fondamentali:
- Incapsulamento: nascondere i dettagli interni di un oggetto e esporre solo un'interfaccia.
- Ereditarietà: creare nuove classi basate su classi esistenti.
- Polimorfismo: usare un'interfaccia comune per operare su oggetti di tipi diversi.
- Astrazione: rappresentare solo le caratteristiche essenziali di un oggetto.
- La OOP si basa su quattro principi fondamentali:
-
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
-
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
-
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
-
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
-
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
-
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!
-
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
-
Metodi speciali:
- Sono metodi predefiniti che iniziano e finiscono con doppi underscore (
__
). - Vengono chiamati automaticamente in situazioni specifiche.
- Sono metodi predefiniti che iniziano e finiscono con doppi underscore (
-
Esempi di metodi speciali:
__init__
: metodo costruttore, chiamato quando si crea un oggetto.__str__
: definisce la rappresentazione in stringa dell'oggetto (usato daprint
).__repr__
: definisce una rappresentazione formale dell'oggetto (usato darepr
).__len__
: definisce il comportamento dilen()
.
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
)
-
Proprietà:
- Le proprietà permettono di definire metodi che si comportano come attributi.
- Si usano i decoratori
@property
,@nome.setter
e@nome.deleter
.
-
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: 25English 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
- What is OOP?
- OOP is based on four fundamental principles:
-
Encapsulation: Hiding the internal details of an object and exposing only an interface.
-
Inheritance: Creating new classes based on existing classes.
-
Polymorphism: Using a common interface to operate on objects of different types.
-
Abstraction: Representing only the essential characteristics of an object.
-
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
- 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
- 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
- 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
- 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
- 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!
- 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
- Special Methods:
- These are predefined methods that start and end with double underscores (
__
). - They are called automatically in specific situations.
- Examples of Special Methods:
__init__
: Constructor method, called when an object is created.__str__
: Defines the string representation of the object (used byprint
).__repr__
: Defines a formal representation of the object (used byrepr
).__len__
: Defines the behavior oflen()
.
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
)
- Properties:
- Properties allow you to define methods that behave like attributes.
- Use the decorators
@property
,@name.setter
and@name.deleter
.
- 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
Posta un commento