【发布时间】:2020-02-05 07:43:32
【问题描述】:
我是 python 类的新手。我正在编写一个将 id 作为参数的类,但是它必须计算另一个依赖于 id 的属性,并且计算可能很激烈。
我的方法是在初始化阶段计算所有内容,尽管这需要时间,为了节省时间,将之前计算的所有内容保存在腌制字典中,如下所示。
import pickle
def intensecomputation(id):
# Compute otherattr, based on id
...
...
return(otherattr)
class myclass:
def __init__(self, id):
self.id = id
# Need to compute self.otherattr that depends on self.id
# Check if I have computed that already
mydict = pickle.load( open( "mydict.p", "rb" ) )
if self.id in mydict:
self.otherattr = mydict[self.id]
else:
self.otherattr = intensecomputation(id)
# Save for later
mydict[self.id] = self.otherattr
pickle.dump( mydict, open( "mydict.p", "wb" ) )
myobject = myclass(10)
# Wait some time here (unless the id 10 is already precalculated in the past and is in the pickled dictionary)
print(myobject.id)
print(myobject.otherattr)
我正在做的事情是一个好习惯吗? __init__ 有什么理由不应该复杂和激烈?我在想,如果是这种情况,那么我可以将intensecomputation 实现为myclass 的一个方法并调用它来填充self.otherattr,如下所示:
myobject = myclass(10)
# myobject.otherattr is empty
print(myobject.id)
myobject.intensecomputation()
# Now myobject.otherattr is created
print(myobject.otherattr)
无论如何,鉴于我的情况,如果有人能向我解释实施myclass 的最佳实践,我将不胜感激。
【问题讨论】:
-
这真的取决于计算是什么以及你的类代表什么。关键决定并不是真的“我是否在
__init__中进行此计算”;诸如“我的对象是否代表其他事物的一部分”和“我的对象实际上是否应该代表其他事物”之类的决定更为重要。 -
不过,拥有一个计算成本高昂的
__init__本身并没有什么坏处。 -
我个人不会将文件 i/o 放入
__init__并且我可能会将otherattr设为属性,这是在您第一次访问文件时从文件中计算/读取的。
标签: python class initialization