Python 2.6.4属性装饰器不起作用 [英] Python 2.6.4 property decorators not working

查看:76
本文介绍了Python 2.6.4属性装饰器不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到了许多示例在线在此论坛中介绍如何使用特殊的 getters 在Python中创建属性>设置者。但是,我无法执行特殊的getter和setter方法,也无法使用 @property 装饰器将属性转换为 readonly

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.

我正在使用Python 2.6.4,这是我的代码。使用了不同的方法来使用属性,但均无效。

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)


推荐答案

PathInfo 必须子类 object

像这样:

class PathInfo(object):

属性仅适用于新样式类。

Properties work only on new style classes.

这篇关于Python 2.6.4属性装饰器不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆