Skip to main content

Property vs. Getters and Setters in Python

In this tutorial, you will learn what the difference is between Python Property and Getters & Setters.
Dec 2018  · 6 min read

What are Getters and Setters?

  • Getters: These are the methods used in Object-Oriented Programming (OOPS) which helps to access the private attributes from a class.
  • Setters: These are the methods used in OOPS feature which helps to set the value to private attributes in a class.

Private Attribute - Encapsulation

If you are not familiar with the private attributes or private methods in Python, read this DataCamp article.

Let's see how you can implement a private attribute 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 has three methods.

  • __init__:- It is used to initialize the attributes or properties of a class.

    • __a:- It is a private attribute.
  • get_a:- It is used to get the values of private attribute a.
  • set_a:- It is used to set the value of a using an object of a class.

You are not able to access the private variables directly in Python. That's why you implemented the getter method.

Let's see how the class works.

## 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

This is how you implement private attributes, getters, and setters in Python. The same process was followed in Java. Let's write the same implementation in a Pythonic way.

class PythonicWay:

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

You don't need any getters, setters methods to access or change the attributes. You can access it directly using the name of the attributes.

Let's see.

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

print(obj.a)
100

What's the difference between the above two classes.

  • SampleClass hides the private attributes and methods. It implements the encapsulation feature of OOPS.
  • PythonicWay doesn't hide the data. It doesn't implement any encapsulation feature.

What's the better to use?

  • This depends on our need. If you want private attributes and methods you can implement the class using setters, getters methods otherwise you will implement using the normal way.

Property

Now, what if you want to have some conditions to set the value of an attribute in the SampleClass.

Let's say if the value we passed is even and positive then we can set it to the attribute, otherwise set the value to 2.

Let's implement this by changing the set_a() method in the 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

Let's check the class by creating an object.

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

print(obj.get_a())
16

Let's see how to implement the above class using the @property decorator.

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 is used to get the value of a private attribute without using any getter methods. We have to put a line @property in front of the method where we return the private variable.

To set the value of the private variable, we use @method_name.setter in front of the method. We have to use it as a setter.

Let's test the class Property to check whether the decorators is working properly or not.

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

print(obj.a)
2

@a.setter will set the value of a by checking the conditions we have mentioned in the method. Another way to use the property is...

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)

Pass all the getter and setter methods to the property and assign it to the variable which you have to use as a class attribute.

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

print(obj.a)
28

Make the setter and getter methods as private to hide them. Let's do it.

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)

Let's check whether it's working properly or not.

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

print(obj.a)
12

Conclusion

You have now seen how you can implement encapsulation in Python and the difference between the setter, getter and, property.

If you are new to Python, I recommend that you take DataCamp's free Introduction to Python course.

If you have any questions regarding the article, please mention them in the comment section. Happy Coding!

Learn more about Python

Introduction to Python

Beginner
4 hr
4.8M learners
Master the basics of data analysis with Python in just four hours. This online course will introduce the Python interface and explore popular packages.
See MoreRight Arrow
Related

Precision-Recall Curve in Python Tutorial

Learn how to implement and interpret precision-recall curves in Python and discover how to choose the right threshold to meet your objective.
Vidhi Chugh's photo

Vidhi Chugh

14 min

An Introduction to Hierarchical Clustering in Python

Understand the ins and outs of hierarchical clustering and its implementation in Python
Zoumana Keita 's photo

Zoumana Keita

17 min

Association Rule Mining in Python Tutorial

Uncovering Hidden Patterns in Python with Association Rule Mining
Moez Ali's photo

Moez Ali

14 min

An Introduction to Python Subprocess: Basics and Examples

Explore our step-by-step guide to running external commands using Python's subprocess module, complete with examples.
Moez Ali's photo

Moez Ali

15 min

Setting Up VSCode For Python: A Complete Guide

Experience a simple, fun, and productive way of Python development by learning about VSCode and its extensionsn and features.
Abid Ali Awan's photo

Abid Ali Awan

16 min

GeoPandas Tutorial: An Introduction to Geospatial Analysis

Get started with GeoPandas, one of the most popular Python libraries for geospatial analysis.
Javier Canales Luna's photo

Javier Canales Luna

15 min

See MoreSee More