Python 2.6.4 property decorators not working

*爱你&永不变心* 提交于 2019-12-08 19:28:21

问题


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)

回答1:


PathInfo must subclass object.

Like this:

class PathInfo(object):

Properties work only on new style classes.



来源:https://stackoverflow.com/questions/2240351/python-2-6-4-property-decorators-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!