Computerish
Computerish

Reputation: 9601

When is a property needed instead of just exposing the variable in Python?

This is the example of using properties given in the Python documentation:

Class C(object):
    def __init__(self):
        self._x = None

    def getx(self):
        return self._x
    def setx(self, value):
        self._x = value
    def delx(self):
        del self._x
    x = property(getx, setx, delx, "I'm the 'x' property.")

As far as I can tell, this behaves just like a regular property-less instance variable:

Class D(object):
    def __init__(self):
        self.x = None

Of course this doesn't have the ability to add additional logic to the getter or setter, but, since there is no difference in how other code interacts with C and D, you could always add a property later if you needed it without breaking any other code.

I know that this creates a problem if you use mutable types that are declared at the class level, i.e.:

class E(object):
    x = [1,2,3]

Apart from that case, though, is it bad practice to leave out the properties until it they are needed or is it acceptable?

Thanks!

Upvotes: 1

Views: 660

Answers (2)

David Marx
David Marx

Reputation: 8558

You use property to evaluate the value an object attribute that is a funciton of other attributes. Consider the following class:

class shape:
    def __init__(self,l,w):
        self.length = l
        self.width  = w
    @property
    def area(self):
        return self.length*self.width

If we change the value of either length or width, the value of area will be updated immediately when we ask for it.

[In:]  s = shape(2,3)

[In:]  print s.length, s.width, s.area
[Out:] 2 3 6

[In:]  s.length = 5

[In:]  print s.length, s.width, s.area
[Out:] 5 3 15

To help clarify how this works, consider the following case: if we try to define area in __init__():

class shape2:
    def __init__(self,l,w):
        self.length = l
        self.width  = w
        self.area = self.length * self.width

area will only be evaluated when the class is instantiated. Changing the values of length or width won't modify the value of area:

[In:]  s = shape2(2,3)

[In:]  print s.length, s.width, s.area
[Out:] 2 3 6

[In:]  s.length = 5

[In:]  print s.length, s.width, s.area
[Out:] 5 3 6

Upvotes: 4

Elazar
Elazar

Reputation: 21655

What I think personally is that Python exposes variables as part of its philosophy, so you do not need to make properties out of everything. You can use properties to add logic to what was once a simple variable, or in order to keep the (client) code clean.

Classes like C in are useless outside tutorials/documentation.

(This is my own opinion. I don't know what is "considered" bad practice, as I am not an experienced developer or something)

Upvotes: 1

Related Questions