-3

I want to access a class attribute in a method, which is associated with the class but since this should be automatic, I use a for-loop. The problem is how to append the attribute name that I get as a string to self so that I could access the attribute: self.str.

Code Snippet : Source Code

Arpit
  • 448
  • 8
  • 26
Mochib
  • 1
  • 4
  • sorry for that , but the image is in the link. thanks. – Mochib May 14 '17 at 10:43
  • 3
    Welcome to Stack Overflow. Please refrain from posting links to images of code. Instead, copy and paste the code relevant to your question directly into your post (of course, this is only a general rule. You should always make sure that the code you post constitutes a [Minimal, Complete, and Verifiable](http://stackoverflow.com/help/mcve) example of the problem you are facing). For reference, please see [How to Ask](http://stackoverflow.com/help/how-to-ask). – stelioslogothetis May 14 '17 at 10:50
  • Try `getattr(self, str)`! – user2390182 May 14 '17 at 10:51
  • @schwobaseggl Thank you for your advice and the function. it work! – Mochib May 14 '17 at 11:36

1 Answers1

1

Attributes of the instance is stored as a dictionary field called __dict__. However a proper way of getting a field dynamically is by using a getattr method. Here is an example:

>>> t = Test()
>>> t.b = 2
>>> getattr(t, 'b')
2
>>> getattr(t, 'c', 'default_value')
'default_value'
taras
  • 3,579
  • 3
  • 26
  • 27