2020年11月21日 星期六

[ Python 常見問題 ] Use of python getattr/setattr for current function

 Source From Here

Question
Is it possible to use getattr/setattr to access a variable in a class function?

Example below. Say I have a class A, that has two methods, func1 and func2 both of which define a variable count of a different type. Is there a way to use getattr in func2 to access the local variable count?

In reality, I have quite a few variables in func2 (that are also defined differently in func1) that I want to loop through using getattr and I'm looking to shorten up my code a bit by using a loop through the variable names.
  1. class A(object):  
  2.   
  3.    def __init__(self):  
  4.       pass  
  5.   
  6.    def func1(self):  
  7.         count = {"A"1"B":2}  
  8.   
  9.    def func2(self):  
  10.         count = [12]  
  11.         mean = [1020]  
  12.         for attr in ("count""mean"):  
  13.            xattr = getattr(self, attr)   ! What do I put in here in place of "self"?  
  14.            xattr.append(99)  

HowTo
  1. import sys  
  2.   
  3. getattr(sys.modules[__name__], attr)  
you can also look up and update the dict returned by globals() directly, ex. this is roughly equivalent to the getattr() above:

沒有留言:

張貼留言

[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...