“派生字段”/“来自计算的类属性”的Python范例

发布于 2024-11-17 07:10:15 字数 737 浏览 4 评论 0原文

比方说,我有一个类计算一个人的保险风险,并且在计算过程中计算了一些其他变量。稍后我需要访问风险和其他变量。

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

泅人 2024-11-24 07:10:15

不,在任何程序中引发 NotYetCalculatedError 都不是合法的事情(除非计算需要花费数小时的时间)。

get_other_var() 应该自动计算风险,

您真正想要做的是在初始化类时运行所有计算,或者如果您不能这样做,您'您想要这样做:

class InsuranceRiskModel(object):
    def __init__(self, person):
        self.person = person
        self.calculated = False

    def calculateModel(self):
        if not self.calculated:
            self.risk = 6
            self.other_var = 5
            self.calculated = True

    @property
    def risk(self):
        self.calculateModel()
        return self.risk

    @property
    def other_var(self):
        self.calculateModel()
        return self.other_var

然后您可以随时访问 InsuranceRiskModel(bob).riskInsuranceRiskModel(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 risk

What 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:

class InsuranceRiskModel(object):
    def __init__(self, person):
        self.person = person
        self.calculated = False

    def calculateModel(self):
        if not self.calculated:
            self.risk = 6
            self.other_var = 5
            self.calculated = True

    @property
    def risk(self):
        self.calculateModel()
        return self.risk

    @property
    def other_var(self):
        self.calculateModel()
        return self.other_var

Then you can access InsuranceRiskModel(bob).risk or InsuranceRiskModel(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

﹏雨一样淡蓝的深情 2024-11-24 07:10:15

为什么不:

def get_other_var():
    # risk hasn't been calculated
    if not self.risk:
        self.risk = self.get_risk()
    return self.other_var

它不是 Python 特有的。如果您所在类别的用户需要 other_var 并且必须在其之前计算 risk,那么最好只是默默地计算它。

Why not:

def get_other_var():
    # risk hasn't been calculated
    if not self.risk:
        self.risk = self.get_risk()
    return self.other_var

?

It is not Python specific. If users of you class need other_var and it is mandatory that risk should be calculated before it, it is better just calculate it silently.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文