0

Basically I am trying to do following code snippet

a = "abc"
all = dir(a)
print all
print a.__add__

The fourth line I would like to do using a variable (in a loop) rather than operating each time, like following (but did not go smooth):

print a.all[0]
tmp = a+'.'+all[0]
print tmp
eval tmp

Please suggest me how can I do this through a loop using a variable like:

  for i in all :
      print a.i
udaya
  • 77
  • 8

2 Answers2

4

Normally, you don't use eval as it is considered unsafe and bad practice overall.

According to python docs dir outputs list of strings, representing valid attributes on the object

Without arguments, return the list of names in the current local scope. With an argument, attempt to return a list of valid attributes for that object.

There's a built-in method to get a member of class/instance by name: getattr (and it's sister methods setattr and hasattr)

a = "QWE"

for member in dir(a):
    print getattr(a, member)

Prints

<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
J0HN
  • 26,063
  • 5
  • 54
  • 85
1

Just needed to cast it all as a string first. Is this what you're looking for?

a = "abc"
all = dir(a)
for i in all :
      print eval( 'a.{1}'.format(a, i) )

Outputs

<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>
...
Green Cell
  • 4,677
  • 2
  • 18
  • 49