程式扎記: [ Python 常見問題 ] How to access object attribute given string corresponding to name of that attribute

標籤

2016年8月26日 星期五

[ Python 常見問題 ] How to access object attribute given string corresponding to name of that attribute

Source From Here
Question
How do you set/get the values of attributes of t given by x.
  1. class test():  
  2.    attr1 = int  
  3.    attr2 = int  
  4.   
  5. t = test()  
  6. x = "attr1"  
How-To
There is built-in functions called getattr and setattr:
  1. getattr(object, attrname)  
  2. setattr(object, attrname, value)  
For example:
>>> class Test:
... name = "John"
... age = 18
... def __init__(self, name, age):
... self.name = name
... self.age = age
... def __str__(self):
... return "%s (%d)" % (self.name, self.age)
...
>>> t = Test("John", 18)
>>> print("Name = %s" % getattr(t, "name"))
Name = John
>>> ageField = "age"
>>> print("Age = %d" % getattr(t, ageField))
Age = 18
>>> setattr(t, "name", "Peter"); setattr(t, ageField, 30)
>>> print("%s" % t)
Peter (30)
>>> print("%s (%d)" % (Test.name, Test.age)) // We modified the field of object, not class!
John (18)


沒有留言:

張貼留言

網誌存檔