“派生字段”/“来自计算的类属性”的Python范例
比方说,我有一个类计算一个人的保险风险,并且在计算过程中计算了一些其他变量。稍后我需要访问风险和其他变量。
class InsuranceRiskModel:
self.risk = None
self.other_var = None
...
def get_risk():
# do a bunch of calculations,
# which in the meantime fills out a bunch of other vars
self.other_var = 5
self.risk = 6
return self.risk
def get_other_var():
# risk hasn't been calculated
if not self.risk:
raise NotYetCalculatedError("Not yet calculated!")
return self.other_var
现在,我在其他一些函数中执行以下操作:
r = InsuranceRiskModel(person)
risk = r.get_risk()
other_var = r.get_other_var()
这对于我想要的程序类型来说是合法的结构吗?只是抛出计算尚未运行的异常,以防止获得虚假值?
I have a class that, let's say, computes a person's insurance risk, and a few other variables are computed during computation. I will need access to the risk and the other variables later.
class InsuranceRiskModel:
self.risk = None
self.other_var = None
...
def get_risk():
# do a bunch of calculations,
# which in the meantime fills out a bunch of other vars
self.other_var = 5
self.risk = 6
return self.risk
def get_other_var():
# risk hasn't been calculated
if not self.risk:
raise NotYetCalculatedError("Not yet calculated!")
return self.other_var
Now in some other function I do:
r = InsuranceRiskModel(person)
risk = r.get_risk()
other_var = r.get_other_var()
Is this a legitimate structure for the sort of program I want? Just throw an exception of the computation hasn't been run, to prevent getting bogus values?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不,在任何程序中引发
NotYetCalculatedError
都不是合法的事情(除非计算需要花费数小时的时间)。get_other_var()
应该自动计算风险,您真正想要做的是在初始化类时运行所有计算,或者如果您不能这样做,您'您想要这样做:
然后您可以随时访问
InsuranceRiskModel(bob).risk
或InsuranceRiskModel(bob).other_var
并且计算将透明地完成。为了回答您更普遍的问题,“[由]存储计算表示的类属性的Python范例”是类属性抽象,涉及透明的用户定义的getter、setter和deleters,如上面所示;更多信息在这里 http://docs.python.org/library/functions.html#property< /a>
No, it is not a legitimate thing to raise a
NotYetCalculatedError
ever, in any program (unless the calculation would take hours of work).get_other_var()
should automatically calculate the riskWhat you actually want to do is run all the calculations when you initialize the class, or if you can't do that, you'll want to do this:
Then you can access
InsuranceRiskModel(bob).risk
orInsuranceRiskModel(bob).other_var
anytime and the calculations will be done transparently.To answer your more general question, the "python paradigm for [class attributes represented by] stored calculations" is the class property abstraction, involving transparent user-defined getters and setters and deleters, as demonstrated above; more info here http://docs.python.org/library/functions.html#property
为什么不:
?
它不是 Python 特有的。如果您所在类别的用户需要
other_var
并且必须在其之前计算risk
,那么最好只是默默地计算它。Why not:
?
It is not Python specific. If users of you class need
other_var
and it is mandatory thatrisk
should be calculated before it, it is better just calculate it silently.