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,
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.
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.
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.
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).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With