2011-11-04 26 views

回答

8

简短的回答:是的

class Person(object): 
    def __init__(self): 
     self.first_name = 'Will' 
     self.second_name = 'Awesome' 

my_guy = Person() 
my_guy.gender = "Male" 
print(my_guy.gender) 

将打印Male

+1

应该注意这个方法:如果你调用Person()。gender',你会得到一个Att ributeError,所以一定要抓住它,如果有可能attr不在那里。 – Daenyth

2

如果你一直不知道,当你写代码这个属性被调用,您可以

my_guy = Person() 

attr = 'secret_habit' # this could be read from file, keybrd etc. 
value = 'wont tell you' 
setattr(my_guy, attr, value) 

print(my_guy.secret_habit) 

我得到“不会告诉你'

+2

忘掉'__dict__'并使用'setattr' /'getattr'。访问实例字典是fragil,它在许多情况下失败(例如'__slots__',旧式类,属性,其他属性访问覆盖,甚至可能更多),这可能不是多数情况,但绝对可以考虑。 – delnan

+0

@delan:按照你的建议修复它。 – yosukesabai

相关问题