Skip to main content
HomeAbout PythonLearn Python

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

BeginnerSkill Level
4 hr
5.1M
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

How to Learn Python From Scratch in 2023: An Expert Guide

Discover how to learn Python, its applications, and the demand for Python skills. Start your Python journey today ​​with our comprehensive guide.
Matt Crabtree's photo

Matt Crabtree

19 min

10 Essential Python Skills All Data Scientists Should Master

All data scientists need expertise in Python, but which skills are the most important for them to master? Find out the ten most vital Python skills in the latest rundown.

Thaylise Nakamoto

9 min

Distributed Processing using Ray framework in Python

Unlocking the Power of Scalable Distributed Systems: A Guide to Ray Framework in Python
Moez Ali's photo

Moez Ali

11 min

Geocoding for Data Scientists: An Introduction With Examples

In this tutorial, you will learn three different ways to convert an address into latitude and longitude using Geopy.
Eugenia Anello's photo

Eugenia Anello

9 min

A Complete Guide to Socket Programming in Python

Learn the fundamentals of socket programming in Python
Serhii Orlivskyi's photo

Serhii Orlivskyi

41 min

Textacy: An Introduction to Text Data Cleaning and Normalization in Python

Discover how Textacy, a Python library, simplifies text data preprocessing for machine learning. Learn about its unique features like character normalization and data masking, and see how it compares to other libraries like NLTK and spaCy.

Mustafa El-Dalil

5 min

See MoreSee More