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)


沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...