Python - 将类属性设置为依赖于同一类中其他属性的值

Rya*_*yan 2 python methods properties class function

很抱歉,如果这已存在于问题档案的某个地方,但我不确定如何询问它并且搜索没有带来任何好的启示.

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

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
Run Code Online (Sandbox Code Playgroud)

哪个回报

{'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
Run Code Online (Sandbox Code Playgroud)

那么在.jd()调用之前,.jd属性(或者我称之为函数或方法?我不确定这里的术语是不正确的).有没有办法我可以以某种方式重写它以使它始终存在基于timetuple类中的当前值,或者在调用.jd属性时让它自己更新?

我知道我可以通过在init(self)部分中创建一个.jd属性然后执行类似的操作来完成它

start = timetuple()
start.jd = julian_date(start)
Run Code Online (Sandbox Code Playgroud)

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

Amb*_*ber 10

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

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"
Run Code Online (Sandbox Code Playgroud)