Programmazione orientata agli oggetti Python

In questo tutorial imparerai a conoscere la programmazione orientata agli oggetti (OOP) in Python e il suo concetto fondamentale con l'aiuto di esempi.

Video: programmazione orientata agli oggetti in Python

Programmazione orientata agli oggetti

Python è un linguaggio di programmazione multi-paradigma. Supporta diversi approcci di programmazione.

Uno degli approcci popolari per risolvere un problema di programmazione è la creazione di oggetti. Questo è noto come programmazione orientata agli oggetti (OOP).

Un oggetto ha due caratteristiche:

  • attributi
  • comportamento

Facciamo un esempio:

Un pappagallo può essere un oggetto, poiché ha le seguenti proprietà:

  • nome, età, colore come attributi
  • cantare, ballare come comportamento

Il concetto di OOP in Python si concentra sulla creazione di codice riutilizzabile. Questo concetto è noto anche come DRY (Don't Repeat Yourself).

In Python, il concetto di OOP segue alcuni principi di base:

Classe

Una classe è un modello per l'oggetto.

Possiamo pensare alla classe come allo schizzo di un pappagallo con etichette. Contiene tutti i dettagli sul nome, colori, taglia, ecc. Sulla base di queste descrizioni, possiamo studiare il pappagallo. Qui, un pappagallo è un oggetto.

L'esempio per la classe di pappagallo può essere:

 classe Parrot: pass

Qui, usiamo la classparola chiave per definire una classe vuota Parrot. Dalla classe, costruiamo istanze. Un'istanza è un oggetto specifico creato da una particolare classe.

Oggetto

Un oggetto (istanza) è un'istanza di una classe. Quando viene definita la classe, viene definita solo la descrizione dell'oggetto. Pertanto, non viene allocata alcuna memoria o archiviazione.

L'esempio per oggetto della classe parrot può essere:

 obj = Pappagallo ()

In questo caso obj è un oggetto di classe Parrot.

Supponiamo di avere dettagli sui pappagalli. Ora mostreremo come costruire la classe e gli oggetti dei pappagalli.

Esempio 1: creazione di classi e oggetti in Python

 class Parrot: # class attribute species = "bird" # instance attribute def __init__(self, name, age): self.name = name self.age = age # instantiate the Parrot class blu = Parrot("Blu", 10) woo = Parrot("Woo", 15) # access the class attributes print("Blu is a ()".format(blu.__class__.species)) print("Woo is also a ()".format(woo.__class__.species)) # access the instance attributes print("() is () years old".format( blu.name, blu.age)) print("() is () years old".format( woo.name, woo.age))

Produzione

 Blu è un uccello Woo è anche un uccello Blu ha 10 anni Woo ha 15 anni

Nel programma sopra, abbiamo creato una classe con il nome Parrot. Quindi, definiamo gli attributi. Gli attributi sono una caratteristica di un oggetto.

Questi attributi sono definiti all'interno del __init__metodo della classe. È il metodo di inizializzazione che viene eseguito per la prima volta non appena viene creato l'oggetto.

Quindi, creiamo istanze della classe Parrot. Qui, blu e woo sono riferimenti (valore) ai nostri nuovi oggetti.

Possiamo accedere all'attributo class usando __class__.species. Gli attributi della classe sono gli stessi per tutte le istanze di una classe. Allo stesso modo, accediamo agli attributi dell'istanza utilizzando blu.namee blu.age. Tuttavia, gli attributi di istanza sono diversi per ogni istanza di una classe.

Per saperne di più su classi e oggetti, vai a Classi e oggetti Python

Metodi

I metodi sono funzioni definite all'interno del corpo di una classe. Sono usati per definire i comportamenti di un oggetto.

Esempio 2: creazione di metodi in Python

 class Parrot: # instance attributes def __init__(self, name, age): self.name = name self.age = age # instance method def sing(self, song): return "() sings ()".format(self.name, song) def dance(self): return "() is now dancing".format(self.name) # instantiate the object blu = Parrot("Blu", 10) # call our instance methods print(blu.sing("'Happy'")) print(blu.dance())

Produzione

 Blu canta "Happy" Blu ora balla

Nel programma sopra, definiamo due metodi ie sing()e dance(). Questi sono chiamati metodi di istanza perché sono chiamati su un oggetto istanza, es blu.

Eredità

Inheritance is a way of creating a new class for using details of an existing class without modifying it. The newly formed class is a derived class (or child class). Similarly, the existing class is a base class (or parent class).

Example 3: Use of Inheritance in Python

 # parent class class Bird: def __init__(self): print("Bird is ready") def whoisThis(self): print("Bird") def swim(self): print("Swim faster") # child class class Penguin(Bird): def __init__(self): # call super() function super().__init__() print("Penguin is ready") def whoisThis(self): print("Penguin") def run(self): print("Run faster") peggy = Penguin() peggy.whoisThis() peggy.swim() peggy.run()

Output

 Bird is ready Penguin is ready Penguin Swim faster Run faster

In the above program, we created two classes i.e. Bird (parent class) and Penguin (child class). The child class inherits the functions of parent class. We can see this from the swim() method.

Again, the child class modified the behavior of the parent class. We can see this from the whoisThis() method. Furthermore, we extend the functions of the parent class, by creating a new run() method.

Additionally, we use the super() function inside the __init__() method. This allows us to run the __init__() method of the parent class inside the child class.

Encapsulation

Using OOP in Python, we can restrict access to methods and variables. This prevents data from direct modification which is called encapsulation. In Python, we denote private attributes using underscore as the prefix i.e single _ or double __.

Example 4: Data Encapsulation in Python

 class Computer: def __init__(self): self.__maxprice = 900 def sell(self): print("Selling Price: ()".format(self.__maxprice)) def setMaxPrice(self, price): self.__maxprice = price c = Computer() c.sell() # change the price c.__maxprice = 1000 c.sell() # using setter function c.setMaxPrice(1000) c.sell()

Output

 Selling Price: 900 Selling Price: 900 Selling Price: 1000

In the above program, we defined a Computer class.

We used __init__() method to store the maximum selling price of Computer. We tried to modify the price. However, we can't change it because Python treats the __maxprice as private attributes.

As shown, to change the value, we have to use a setter function i.e setMaxPrice() which takes price as a parameter.

Polymorphism

Polymorphism is an ability (in OOP) to use a common interface for multiple forms (data types).

Suppose, we need to color a shape, there are multiple shape options (rectangle, square, circle). However we could use the same method to color any shape. This concept is called Polymorphism.

Example 5: Using Polymorphism in Python

 class Parrot: def fly(self): print("Parrot can fly") def swim(self): print("Parrot can't swim") class Penguin: def fly(self): print("Penguin can't fly") def swim(self): print("Penguin can swim") # common interface def flying_test(bird): bird.fly() #instantiate objects blu = Parrot() peggy = Penguin() # passing the object flying_test(blu) flying_test(peggy)

Output

 Parrot can fly Penguin can't fly

In the above program, we defined two classes Parrot and Penguin. Each of them have a common fly() method. However, their functions are different.

Per utilizzare il polimorfismo, abbiamo creato un'interfaccia comune, ovvero una flying_test()funzione che accetta qualsiasi oggetto e chiama il fly()metodo dell'oggetto . Pertanto, quando abbiamo passato gli oggetti blu e peggy nella flying_test()funzione, è stata eseguita in modo efficace.

Punti chiave da ricordare:

  • La programmazione orientata agli oggetti rende il programma facile da capire oltre che efficiente.
  • Poiché la classe è condivisibile, il codice può essere riutilizzato.
  • I dati sono sicuri e protetti con l'astrazione dei dati.
  • Il polimorfismo consente la stessa interfaccia per oggetti diversi, quindi i programmatori possono scrivere codice efficiente.

Articoli interessanti...