必须显式地调用check_mood来更改对象的属性。参见下面的代码。在from random import randint
class Foo(object):
def __init__(self, mood):
self.__mood = mood
self.__selection = {
1:'happy',
2:'hungry',
3:'sleepy',
4:'angry',
5:'bored'
}
def check_mood(self):
m = randint(1,5)
self.__mood = self.__selection[m]
def get_mood(self):
return self.__mood
mood = 'happy'
f = Foo(mood)
print 'This is your previous mood:', f.get_mood()
f.check_mood() # This rerolls the mood.
print 'This is your current mood:', f.get_mood()
# This is your previous mood: happy
# This is your current mood: bored
否则,如果你想让它改变“幕后”,我建议调用check_moodinsideget_mood(或者干脆把check_mood完全去掉,把它的代码放在get_mood中)。在
但是,get_mood的定义方式使其修改原始的self.__mood,一旦调用get_mood,就会将传入的原始参数呈现为丢失。在