這是有效的。瞭解是否需要明確添加()以獲得評估
class Bob(object):
def __init__(self, xvals):
self.xvals = xvals
def get_xmax(self):
return max(self.xvals)
bob = Bob([3, 1, 2])
print bob.get_xmax() # returns 3
bob.xvals = [-3, -1, -2]
print bob.get_xmax() # returns -1
這並不是因爲max()
在實例化過程中僅評估一次。
class Bob(object):
def __init__(self, xvals):
self.xvals = xvals
self.xmax = max(self.xvals) # evaluated during instantiation
bob = Bob([3, 1, 2])
print bob.xmax # returns 3
bob.xvals = [-3, -1, -2]
print bob.xmax # still returns 3, not -1
有一個簡單的(和Python的)方式來獲得bob.xmax
當前的最大與返回了()
或者是點 - 潛在的昂貴的操作應要求()
爲你所要求的多提醒只是一個對象的引用?
您可以引入getter和setter方法並在setter方法中更新'xmax'。 – Michael