Vai al contenuto principale

Property vs. Getter e Setter in Python

In questo tutorial imparerai qual è la differenza tra Property di Python e Getter & Setter.
· 6 min leggi

Scopri con l'IA

Cosa sono i Getter e i Setter?

  • Getter: sono i metodi usati nella programmazione orientata agli oggetti (OOP) che permettono di accedere agli attributi privati di una classe.
  • Setter: sono i metodi usati nell’OOP che permettono di assegnare un valore agli attributi privati di una classe.

Attributo privato - Incapsulamento

Se non conosci gli attributi privati o i metodi privati in Python, leggi questo articolo di DataCamp.

Vediamo come puoi implementare un attributo privato in Python.

class SampleClass:

    def __init__(self, a):
        ## private varibale or property in Python
        self.__a = a

    ## getter method to get the properties using an object
    def get_a(self):
        return self.__a

    ## setter method to change the value 'a' using an object
    def set_a(self, a):
        self.__a = a

SampleClass ha tre metodi.

  • __init__:- serve a inizializzare gli attributi o le proprietà di una classe.

    • __a:- è un attributo privato.
  • get_a:- serve per ottenere i valori dell’attributo privato a.
  • set_a:- serve per impostare il valore di a usando un oggetto della classe.

In Python non puoi accedere direttamente alle variabili private. Ecco perché hai implementato il metodo getter.

Vediamo come funziona la classe.

## creating an object
obj = SampleClass(10)

## getting the value of 'a' using get_a() method
print(obj.get_a())

## setting a new value to the 'a' using set_a() method
obj.set_a(45)

print(obj.get_a())
10
45

Ecco come implementi attributi privati, getter e setter in Python. Lo stesso processo veniva seguito in Java. Scriviamo la stessa implementazione in modo più pythonic.

class PythonicWay:

    def __init__(self, a):
        self.a = a

Non ti servono metodi getter o setter per accedere o modificare gli attributi. Puoi accedervi direttamente usando il nome degli attributi.

Vediamo.

## Creating an object for the 'PythonicWay' class
obj = PythonicWay(100)

print(obj.a)
100

Qual è la differenza tra le due classi sopra?

  • SampleClass nasconde attributi e metodi privati. Implementa la caratteristica di incapsulamento dell’OOP.
  • PythonicWay non nasconde i dati. Non implementa alcuna caratteristica di incapsulamento.

Qual è meglio usare?

  • Dipende dalle esigenze. Se ti servono attributi e metodi privati puoi implementare la classe usando metodi setter e getter, altrimenti la implementerai nel modo normale.

Property

Ora, e se volessi imporre alcune condizioni per impostare il valore di un attributo in SampleClass?

Supponiamo che, se il valore passato è pari e positivo, allora possiamo assegnarlo all’attributo, altrimenti impostiamo il valore a 2.

Implementiamo questo modificando il metodo set_a() in SampleClass.

class SampleClass1:

    def __init__(self, a):
        ## calling the set_a() method to set the value 'a' by checking certain conditions
        self.set_a(a)

    ## getter method to get the properties using an object
    def get_a(self):
        return self.__a

    ## setter method to change the value 'a' using an object
    def set_a(self, a):

        ## condition to check whether 'a' is suitable or not
        if a > 0 and a % 2 == 0:
            self.__a = a
        else:
            self.__a = 2

Verifichiamo la classe creando un oggetto.

## creating an object for the class 'SampleClass1'
obj = SampleClass1(16)

print(obj.get_a())
16

Vediamo come implementare la classe sopra usando il decorator @property.

class Property:

    def __init__(self, var):
        ## initializing the attribute
        self.a = var

    @property
    def a(self):
        return self.__a

    ## the attribute name and the method name must be same which is used to set the value for the attribute
    @a.setter
    def a(self, var):
        if var > 0 and var % 2 == 0:
            self.__a = var
        else:
            self.__a = 2

@property serve per ottenere il valore di un attributo privato senza usare metodi getter. Dobbiamo mettere una riga @property davanti al metodo in cui restituiamo la variabile privata.

Per impostare il valore della variabile privata, usiamo @method_name.setter davanti al metodo. Lo usiamo come setter.

Testiamo la classe Property per verificare se i decorator funzionano correttamente.

## creating an object for the class 'Property'
obj = Property(23)

print(obj.a)
2

@a.setter imposterà il valore di a verificando le condizioni indicate nel metodo. Un altro modo di usare property è...

class AnotherWay:

    def __init__(self, var):
        ## calling the set_a() method to set the value 'a' by checking certain conditions
        self.set_a(var)

    ## getter method to get the properties using an object
    def get_a(self):
        return self.__a

    ## setter method to change the value 'a' using an object
    def set_a
    (self, var):

        ## condition to check whether var is suitable or not
        if var > 0 and var % 2 == 0:
            self.__a = var
        else:
            self.__a = 2

    a = property(get_a, set_a)

Passa tutti i metodi getter e setter a property e assegnala alla variabile che vuoi usare come attributo della classe.

## creating an object for the 'AnotherWay' class
obj = AnotherWay(28)

print(obj.a)
28

Rendi i metodi setter e getter privati per nasconderli. Facciamolo.

class FinalClass:

    def __init__(self, var):
        ## calling the set_a() method to set the value 'a' by checking certain conditions
        self.__set_a(var)

    ## getter method to get the properties using an object
    def __get_a(self):
        return self.__a

    ## setter method to change the value 'a' using an object
    def __set_a(self, var):

        ## condition to check whether var is suitable or not
        if var > 0 and var % 2 == 0:
            self.__a = var
        else:
            self.__a = 2

    a = property(__get_a, __set_a)

Verifichiamo se funziona correttamente.

## creating an object for the 'AnotherWay' class
obj = FinalClass(12)

print(obj.a)
12

Conclusione

Hai visto come implementare l’incapsulamento in Python e la differenza tra setter, getter e property.

Se sei alle prime armi con Python, ti consiglio di seguire il corso gratuito di DataCamp Introduction to Python.

Se hai domande sull’articolo, scrivile nei commenti. Buon coding!

Argomenti

Correlato