基本上我正在尝试执行以下代码段
a = "abc"
all = dir(a)
print all
print a.__add__
第四行我想用变量(在循环中)而不是每次操作,如下所示(但没有顺利):
print a.all[0]
tmp = a+'.'+all[0]
print tmp
eval tmp
请建议我如何通过使用变量的循环来完成此操作:
for i in all :
print a.i
答案 0 :(得分:4)
通常情况下,您不会使用eval
,因为它被认为是不安全和整体不良做法。
根据python docs dir
输出字符串列表,表示对象上的有效属性
不带参数,返回当前本地范围内的名称列表。 使用参数,尝试返回该对象的有效属性列表。
有一个内置方法可以按名称获取类/实例的成员:getattr
(以及它的姐妹方法setattr
和hasattr
)< / p>
a = "QWE"
for member in dir(a):
print getattr(a, member)
打印
<method-wrapper '__add__' of str object at 0x0000000002FF1688>
<class 'str'>
<method-wrapper '__contains__' of str object at 0x0000000002FF1688>
<method-wrapper '__delattr__' of str object at 0x0000000002FF1688>
<built-in method __dir__ of str object at 0x0000000002FF1688>
str(object='') -> str
str(bytes_or_buffer[, encoding[, errors]]) -> str
答案 1 :(得分:1)
首先需要将它全部转换为字符串。这是你在找什么?
a = "abc"
all = dir(a)
for i in all :
print eval( 'a.{1}'.format(a, i) )
输出
<method-wrapper '__add__' of str object at 0x1ea7698>
<type 'str'>
<method-wrapper '__contains__' of str object at 0x1ea7698>
<method-wrapper '__delattr__' of str object at 0x1ea7698>
str(object) -> string
Return a nice string representation of the object.
If the argument is a string, the return value is the same object.
<method-wrapper '__eq__' of str object at 0x1ea7698>
<built-in method __format__ of str object at 0x1ea7698>
<method-wrapper '__ge__' of str object at 0x1ea7698>
<method-wrapper '__getattribute__' of str object at 0x1ea7698>
<method-wrapper '__getitem__' of str object at 0x1ea7698>
<built-in method __getnewargs__ of str object at 0x1ea7698>
<method-wrapper '__getslice__' of str object at 0x1ea7698>
<method-wrapper '__gt__' of str object at 0x1ea7698>
...