Why do we need a property in Python?

I understand that one of the main uses of a property is validation and formatting. For example, I have a User class shown below. And I want the first and last name to be capitalized when they are set. Why do I need a property if I can write the following code to achieve the same formatting result?

class User:
    def __init__(self, firstname, lastname):
        self.firstname = firstname
        self.lastname = lastname

    def __setattr__(self, attr, value):
        if attr == 'firstname':
            self.__dict__[attr] = value.capitalize()
        elif attr == 'lastname':
            self.__dict__[attr] = value.capitalize()

      

+3


source to share


3 answers


You're right, you don't need properties to do validation when setting an attribute or to do custom behavior when looking up attributes. But properties are more readable and nicer to write. I stick with the use __getattr__

also __setattr__

in cases where you want to dynamically access attributes (i.e. you don't know what attributes you have at the time of class definition). Otherwise, use properties as they are a very recognizable python idiom.

In fact, in this case, when you have two properties that do the same check, I can use a handle:

class NameDescriptor(object):

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

    def __get__(self, obj, objtype):
        return getattr(obj, self.key)

    def __set__(self, obj, val):
        setattr(obj, self.key, val.capitalize())

class User(object):

    firstname = NameDescriptor('_firstname')
    lastname = NameDescriptor('_lastname')

    def __init__(self, first, last):
        self.firstname = first
        self.lastname = last

      



Demonstration of how it works:

>>> user = User('steve', 'martin')
>>> user.firstname
'Steve'
>>> user.firstname = 'dean'
>>> user.firstname
'Dean'

      

+4


source


I would use them because they are more meaningful. And the properties are listed directly below the class, and what you are doing is displayed below the function. This means that a person can see what attributes each object should have, as well as a computer: you add an attribute to the class definition, so it's not just a thing that all users have a match for.



Also, the implementation of properties can be efficient. You are doing name lookups in Python, and the more names you have, the more checks you will need. By programming at a higher level, you let the interpreter decide how properties are implemented, and a newer interpreter can use smarter tricks to do this.

+1


source


The really cool thing about properties in Python is that you can go back to the mess you've created in your application in the past and fix it without breaking existing code.

In Java, for example, by setting a class variable to private, you provide getter and setter functions, and usually insert some logic into them to avoid absurd values.

In Python, since class variables are public by default, it's very easy to create a situation where users of your class find all sorts of creative ways to enter absurd values.

By the time you realize that if you significantly change your application logic to prevent absurd thesis meanings, you are likely to create a new version of your application that will not be backward compatible with the first. This usually makes users very unhappy.

Properties give you a way to get around this: eliminate the clutter while maintaining backward compatibility.

If you need more information on how this works, check out this page:

' http://www.programiz.com/python-programming/property '

it explains well.

+1


source







All Articles