Skip to main content
HomeTutorialsPython

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!

Topics

Learn more about Python

Certification available

Course

Introduction to Python

4 hr
5.4M
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 DetailsRight Arrow
Start Course
See MoreRight Arrow
Related

tutorial

Writing Custom Context Managers in Python

Learn the advanced aspects of resource management in Python by mastering how to write custom context managers.
Bex Tuychiev's photo

Bex Tuychiev

tutorial

How to Convert a List to a String in Python

Learn how to convert a list to a string in Python in this quick tutorial.
Adel Nehme's photo

Adel Nehme

tutorial

A Comprehensive Tutorial on Optical Character Recognition (OCR) in Python With Pytesseract

Master the fundamentals of optical character recognition in OCR with PyTesseract and OpenCV.
Bex Tuychiev's photo

Bex Tuychiev

11 min

tutorial

Encapsulation in Python Object-Oriented Programming: A Comprehensive Guide

Learn the fundamentals of implementing encapsulation in Python object-oriented programming.
Bex Tuychiev's photo

Bex Tuychiev

11 min

tutorial

Python KeyError Exceptions and How to Fix Them

Learn key techniques such as exception handling and error prevention to handle the KeyError exception in Python effectively.
Javier Canales Luna's photo

Javier Canales Luna

6 min

code-along

Full Stack Data Engineering with Python

In this session, you'll see a full data workflow using some LIGO gravitational wave data (no physics knowledge required). You'll see how to work with HDF5 files, clean and analyze time series data, and visualize the results.
Blenda Guedes's photo

Blenda Guedes

See MoreSee More