Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 2.6.4 property decorators not working

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)
like image 215
Matt Norris Avatar asked Feb 10 '10 21:02

Matt Norris


People also ask

Is @property a decorator?

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!

What is Property () 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 is Deleter in Python?

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.

How do you define a class property in Python?

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#.


1 Answers

PathInfo must subclass object.

Like this:

class PathInfo(object):

Properties work only on new style classes.

like image 159
gruszczy Avatar answered Sep 22 '22 04:09

gruszczy