Julius F
Julius F

Reputation: 3444

Use of properties in python like in example C#

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,

Upvotes: 10

Views: 4275

Answers (3)

Duncan
Duncan

Reputation: 95652

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.

Upvotes: 2

Philipp
Philipp

Reputation: 49812

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

Upvotes: 15

Tony Veijalainen
Tony Veijalainen

Reputation: 5555

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

Upvotes: 7

Related Questions