Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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,

like image 734
Julius F Avatar asked Jul 24 '10 11:07

Julius F


People also ask

What is the use of properties in Python?

Python's property() is the Pythonic way to avoid formal getter and setter methods in your code. This function allows you to turn class attributes into properties or managed attributes. Since property() is a built-in function, you can use it without importing anything.

What is property type in Python?

Python property() function returns the object of the property class and it is used to create property of a class. Syntax: property(fget, fset, fdel, doc) Parameters: fget() – used to get the value of attribute. fset() – used to set the value of attribute.

What are properties and attributes in Python?

Attributes are described by data variables for example like name, age, height etc. Properties are special kind of attributes which have getter, setter and delete methods like __get__, __set__ and __delete__ methods.

What are the properties of a variable in Python?

A variable name must start with a letter or the underscore character. A variable name cannot start with a number. A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ ). Variable names are case-sensitive (name, Name and NAME are three different variables).


1 Answers

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
like image 79
Philipp Avatar answered Sep 17 '22 11:09

Philipp