在 python 中,编写这样的 __init__
定义是不是不好的形式:
class someFileType(object):
def __init__(self, path):
self.path = path
self.filename = self.getFilename()
self.client = self.getClient()
self.date = self.getDate()
self.title = self.getTitle()
self.filetype = self.getFiletype()
def getFilename(self):
'''Returns entire file name without extension'''
filename = os.path.basename(self.path)
filename = os.path.splitext(filename)
filename = filename[0]
return filename
def getClient(self):
'''Returns client name associated with file'''
client = self.filename.split()
client = client[1] # Assuming filename is formatted "date client - docTitle"
return client
初始化变量在哪里调用返回字符串的函数?或者它被认为是惰性编码?这主要是为了避免在我想引用文件的某些方面时将 something.filetype
写成 something.getFiletype()
。
这段代码是将文件按客户端分类到文件夹中,然后按文档类型分类,然后根据文件名中的数据进行其他操作。
最佳答案
不,我不明白为什么那会是一种糟糕的形式。事实上,在创建实例时只计算一次这些值可能是个好主意。
您还可以通过使用缓存 property
s 将计算推迟到需要的时候:
class SomeFileType(object):
_filename = None
_client = None
def __init__(self, path):
self.path = path
@property
def filename(self):
if self._filename is None:
filename = os.path.basename(self.path)
self._filename = os.path.splitext(filename)[0]
return self._filename
@property
def client(self):
'''Returns client name associated with file'''
if self._client is None:
client = self.filename.split()
self._client = client[1] # Assuming filename is formatted "date client - docTitle"
return self._client
现在,访问somefiletypeinstance.client
将根据需要触发self.filename
的计算,并缓存它自己的计算结果。
在这种特定情况下,您可能还想使 .path
成为一个属性;一个带有清除缓存值的 setter :
class SomeFileType(object):
_filename = None
_client = None
def __init__(self, path):
self._path = path
@property
def path(self):
return self._path
@path.setter
def path(self, value):
# clear all private instance attributes
for key in [k for k in vars(self) if k[0] == '_']:
delattr(self, key)
self._path = value
@property
def filename(self):
if self._filename is None:
filename = os.path.basename(self.path)
self._filename = os.path.splitext(filename)[0]
return self._filename
@property
def client(self):
'''Returns client name associated with file'''
if self._client is None:
client = self.filename.split()
self._client = client[1] # Assuming filename is formatted "date client - docTitle"
return self._client
因为基于 property
的缓存确实增加了一些复杂的开销,你需要考虑它是否真的值得你花时间;对于您具体的简单示例,它可能不是。属性的计算成本确实非常低,除非您计划创建大量这些类,否则与必须维护按需缓存属性的心理成本相比,提前计算属性的开销可以忽略不计。
关于Python 类 __init__ 布局?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16040784/