I've seen many examples online and in this forum of how to create properties in Python with special getters and setters. However, I can't get the special getter and setter methods to execute, nor can I use the @property decorator to transform a property as readonly.
I'm using Python 2.6.4 and here is my code. Different methods to use properties are employed, but neither work.
class PathInfo:
def __init__(self, path):
self.setpath(path)
def getpath(self):
return self.__path
def setpath(self, path):
if not path:
raise TypeError
if path.endswith('/'):
path = path[:-1]
self.__path = path
self.dirname = os.path.dirname(path)
self.basename = os.path.basename(path)
(self.rootname, self.dext) = os.path.splitext(self.basename)
self.ext = self.dext[1:]
path = property(fget=getpath, fset=setpath)
@property
def isdir(self):
return os.path.isdir(self.__path)
@property
def isfile(self):
return os.path.isfile(self.__path)
The @property is a built-in decorator for the property() function in Python. It is used to give "special" functionality to certain methods to make them act as getters, setters, or deleters when we define properties in a class. Now that you are familiar with decorators, let's see a real scenario of the use of @property!
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.
Just like the setter method, python has deleter method which is used to delete the property of a class. The syntax of declaring the deleter method decorator is: @property-name. deleter. Once the property is deleted, it cannot be accessed using the same instance.
In Python, a property in the class can be defined using the property() function. The property() method in Python provides an interface to instance attributes. It encapsulates instance attributes and provides a property, same as Java and C#.
PathInfo must subclass object.
Like this:
class PathInfo(object):
Properties work only on new style classes.
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