-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

4
  • sorry for that , but the image is in the link. thanks. Commented May 14, 2017 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 example of the problem you are facing). For reference, please see How to Ask. Commented May 14, 2017 at 10:50
  • Try getattr(self, str)! Commented May 14, 2017 at 10:51
  • @schwobaseggl Thank you for your advice and the function. it work! Commented May 14, 2017 at 11:36

1 Answer 1

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'
Sign up to request clarification or add additional context in comments.

1 Comment

It work! Thank you.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.