7

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)
Community
  • 1
  • 1
Matt Norris
  • 8,596
  • 14
  • 59
  • 90

1 Answers1

22

PathInfo must subclass object.

Like this:

class PathInfo(object):

Properties work only on new style classes.

gruszczy
  • 40,948
  • 31
  • 128
  • 181