问题描述
我在和上看到了很多关于如何使用特殊的getter和setter在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)
1楼
PathInfo必须是对象的子类。
像这样:
class PathInfo(object):
属性仅适用于新样式类。