views:

86

answers:

3

Hi there,

I currently work with Python for a while and I came to the point where I questioned myself whether I should use "Properties" in Python as often as in C#. In C# I've mostly created properties for the majority of my classes.

It seems that properties are not that popular in python, am I wrong? How to use properties in Python?

regards,

+3  A: 

I would you recommend to read this, even it is directed to Java progrmamers: Python Is Not Java

Tony Veijalainen
+1 Thats a worthwhile read.
volting
+3  A: 

Properties are often no required if all you do is set and query member variables. Because Python has no concept of encapsulation, all member variables are public and often there is no need to encapsulate accesses. However, properties are possible, perfectly legitimate and popular:

class C(object):
    def __init__(self):
        self._x = 0

    @property
    def x(self):
        return self._x

    @x.setter
    def x(self, value):
        if value <= 0:
            raise ValueError("Value must be positive")
        self._x = value

o = C()
print o.x
o.x = 5
print o.x
o.x = -2
Philipp
+1  A: 

If you make an attribute public in C# then later need to change it into a property you also need to recompile all code that uses the original class. This is bad, so make any public attributes into properties from day one 'just in case'.

If you have an attribute that is used from other code then later need to change it into a property then you just change it and nothing else needs to happen. So use ordinary attributes until such time as you find you need something more complicated.

Duncan