Python 2.6.4属性修饰器无法正常工作

Mat*_*ris 7 python properties decorator

我在网上在这个论坛上看到了很多关于如何使用特殊的gettersetter在Python中创建属性的例子.但是,我无法获取执行的特殊getter和setter方法,也无法使用@property装饰器将属性转换为readonly.

我正在使用Python 2.6.4,这是我的代码.使用不同的使用属性的方法,但都不起作用.

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)
Run Code Online (Sandbox Code Playgroud)

gru*_*czy 21

PathInfo必须是对象的子类.

像这样:

class PathInfo(object):
Run Code Online (Sandbox Code Playgroud)

属性仅适用于新样式类.

  • 不仅是属性,还有各种描述符. (4认同)