标签云

微信群

扫码加入我们

WeChat QR Code

Is there a way to loop over attributes, without retyping a long name?I'm trying to print the value(s) stored in an object. The problem is that I don't know what attribute stores the value, or even what the attributes are. I used dir(MyFunc) to find what the attributes are, but every time, there are more and more attributes to look through.>>> print dir(MyFunc)['__class__', '__delattr__', '__dict__', '__doc__', '__format__','__getattribute__', 'data']>>> print dir(MyFunc.data)['__call__', '__class__', '__closure__', '__code__', '__defaults__','__delattr__', '__dict__', '__doc__', '__format__', '__get__','__getattribute__', '__globals__', '__hash__', '__init__', '__module__','__name__', '__new__', '__reduce__', '__reduce_ex__', '__repr__','__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'func_closure','func_code', 'func_defaults', 'func_dict', 'func_globals', 'func_name']So I tried to use a for loop to print the attributes of each attribute, but I can't find how to do this. >>> for x in ['func_closure','func_code','func_defaults','func_dict']:y = MyFunc.data.xprint yTraceback (most recent call last):File "myFile.py", line 127, in setUpy = MyFunc.data.xAttributeError: 'function' object has no attribute 'x'


use getattr

2019年04月22日26分01秒