Python property() — What You Always Wanted to Know But Never Dared to Ask

Object-orientation is great way to encapsulate data in your application. This minimizes complexity and adheres to good software engineering principles.

However, attributes in Python can be easily accessed from the outside—they’re not really encapsulated. That’s one of the reason the property() built-in function exists: it allows you to truly encapsulate data with the means of private attributes that you can access via getter and setter functions from the outside.

Python property()

Python’s built-in property() function creates and returns a new property attribute that should be private, i.e., only accessible via defined functions. As arguments, you pass three functions to get, set, and delete the attribute value—as well as the fourth docstring argument. All four arguments are None per default.

Here’s the formal syntax and argument list of the property() function:

property(fget=None, fset=None, fdel=None, doc=None)
ArgumentsfgetCallable function object for getting an attribute value. Returns the attribute value.
fsetCallable function object for setting an attribute value. No return value required.
fdelCallable function object for deleting an attribute value. No return value required.
docString describing the documentation of the attribute.
Return ValuepropertyReturns new object of class property that allows you to access the property from the outside via defined getter and setter methods.

Python property() — Usage Examples

Learn by example! In the following, we’re going to explore an example of why and how to use the property() built-in function.

Have a look at this simple Car class for which we create a “secret” _owner attribute—note the prefixed underscore to discourage external access:

class Car:

    def __init__(self):
        self._owner = None

    def get_owner(self):
        return self._owner

    def set_owner(self, name):
        self._owner = name

    def delete_owner(self):
        del self._owner


porsche = Car()
porsche.set_owner('Chris')
print(porsche.get_owner())
# Chris

The owner attribute has a getter function, a setter function, and a delete function that removes the attribute.

This follows the guidelines of object orientation to allow external access of object attributes only via functions rather than directly via porsche._owner. However, using complicated getter and setter function names can be a pain. That’s why you can also add an additional line using the property() function to make _owner a property rather than just an attribute:

class Car:

    def __init__(self):
        self._owner = None

    def get_owner(self):
        return self._owner

    def set_owner(self, name):
        self._owner = name

    def delete_owner(self):
        del self._owner

    # Creates a property: Car.owner
    owner = property(get_owner,
                     set_owner,
                     delete_owner,
                     'Owner of the car')
    

porsche = Car()
porsche.owner = 'Chris'
print(porsche.owner)
# Chris

This greatly facilitates access of the attribute. Instead of calling the clunky porsche._owner or even porsche.get_owner(), you can now call porsche.owner as if owner was an attribute. Python then internally calls the defined getter and setter functions to modify, access, or delete the attribute _owner.

Python property() — Video


Check out my new Python book Python One-Liners (Amazon Link).

If you like one-liners, you’ll LOVE the book. It’ll teach you everything there is to know about a single line of Python code. But it’s also an introduction to computer science, data science, machine learning, and algorithms. The universe in a single line of Python!

The book was released in 2020 with the world-class programming book publisher NoStarch Press (San Francisco).

Publisher Link: https://nostarch.com/pythononeliners

Python property() — Interactive Code Exercise

Let’s have a look at a practical exercise:

Exercise: Replace both occurrences of ??? with some code to make you the owner of the Porsche!


Summary

Object-orientation is great way to encapsulate data in your application. This minimizes complexity and adheres to good software engineering principles.

However, attributes in Python can be easily accessed from the outside—they’re not really encapsulated. That’s one of the reason the property() built-in function exists: it allows you to truly encapsulate data with the means of private attributes that you can access via getter and setter functions from the outside.

Python’s built-in property() function creates and returns a new property attribute that should be private, i.e., only accessible via defined functions. As arguments, you pass three functions to get, set, and delete the attribute value—as well as the fourth docstring argument. All four arguments are None per default.


I hope you enjoyed the article! To improve your Python education, you may want to join the popular free Finxter Email Academy:

Do you want to boost your Python skills in a fun and easy-to-consume way? Consider the following resources and become a master coder!

Where to Go From Here?

Enough theory. Let’s get some practice!

Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.

To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

You build high-value coding skills by working on practical coding projects!

Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?

🚀 If your answer is YES!, consider becoming a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!