views:

245

answers:

1

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)
+12  A: 

PathInfo must subclass object.

Like this:

class PathInfo(object):

Properties work only on new style classes.

gruszczy
Not just properties, but descriptors of all kinds.
Ignacio Vazquez-Abrams
Another option is to put `__metaclass__=type` at the top of the file, which will make all the classes newstyle. I think it's better to be explicit for each class though
gnibbler
Or you can put this `__metaclass__` into the class instead of putting it at the top of the file. This way only one class will have it.
gruszczy
What a difference a word makes! Thanks for all of your tips.
Wraith