Python-设置类属性以依赖于同一类中其他属性的值 [英] Python - Set class property to depend on values of other properties in the same class

查看:122
本文介绍了Python-设置类属性以依赖于同一类中其他属性的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很抱歉,问题档案库中已经存在该文件,但是我不确定如何提出问题,并且搜索并没有带来任何重大启示.

Sorry if this already exists somewhere in the question archives, but I'm not sure how to ask it and searching didn't lead to any great revelations.

在Python(2.6.x)中,我创建了一个类

In Python (2.6.x) I have created a class

class timetuple(object):
    def __init__(self):
        self.weekday = 6
        self.month   = 1
        self.day     = 1
        self.year    = 2011
        self.hour    = 0
        self.min     = 0
        self.sec     = 0
    def jd(self):
        self.jd = julian_date(self)

def julian_date(obj):
    (Code to calculate a Julian Date snipped)

start = timetuple()
start.day   = 23
start.month = 2
start.year  = 2011
start.hour  = 13
start.min   = 30
start.sec   = 0

print start.__dict__
start.jd()
print start.__dict__
print start.jd

返回哪个

{'hour': 13, 'min': 30, 'month': 2, 'sec': 0, 'weekday': 6, 'year': 2011, 'date': 23, 'day': 1}
{'hour': 13, 'min': 30, 'month': 14, 'jd': 2455594.0625, 'sec': 0, 'weekday': 6, 'year': 2010, 'date': 23, 'day': 1}
2455594.0625

因此,在start.jd()调用之前,不存在.jd属性(或者我称其为函数还是方法?我不确定这里的术语).我有办法以某种方式重写它,使其根据timetuple类中的当前值始终存在,或者让它在调用.jd属性时更新自身吗?

So the .jd property (or do I call this a function or a method? I'm unsure of the lingo here honestly) doesn't exist before the start.jd() call. Is there a way I can somehow rewrite this to make it always exist based on the current values in the timetuple class, or have it update itself when the .jd property is called?

我知道我可以做很多事情,只需在 init (self)部分中创建一个.jd属性,然后执行类似的操作

I know I can do it the long way by just making a .jd property in the init(self) section and then do something like

start = timetuple()
start.jd = julian_date(start)

但是我想知道如何诚实地更好地设置我的课程:)

but I'd like to know how to set up my classes better honestly :)

推荐答案

您要实际定义一个属性,而不是一个变量:

You want to actually define a property, as opposed to a variable:

class A(object):

    def __init__(self):
        self.a = 1
        self.b = 1

    @property
    def a_plus_b(self):
        return self.a + self.b

foo = A()
print foo.a_plus_b # prints "2"
foo.a = 3
print foo.a_plus_b # prints "4"
foo.b = 4
print foo.a_plus_b # prints "7"

这篇关于Python-设置类属性以依赖于同一类中其他属性的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆