1

I would like to be able to select the class' property by it's name. This is my code:

class example(object):
    def __init__(self):
        self.one = "1"
        self.two = "2"

x = example()
list = ["one", "two"]
# I want to get x.one here by referring to it by list[0]

How can I do this?

Worked example:

class example(object):
    def __init__(self):
        self.one = "one"
        self.two = "two"

    def test(self):
        list = ["one", "two"]
        print(getattr(self, list[1]))

x = example()

x.test()
John
  • 435
  • 6
  • 15
  • Welcome to StackOverflow. Please read and follow the posting guidelines in the help documentation, as suggested when you created this account. [Minimal, complete, verifiable example](http://stackoverflow.com/help/mcve) applies here. We cannot effectively help you until you post your MCVE code and accurately describe the problem. We should be able to paste your posted code into a text file and reproduce the problem you described. – Prune Apr 25 '18 at 21:02
  • 1
    What are you trying to do? Your terminology doesn't match the code you posted, and that code is unclear. – Prune Apr 25 '18 at 21:03
  • I have fixed the question for you John, hopefully that's what you're trying to ask. The answers are already available below – bosnjak Apr 25 '18 at 21:04

3 Answers3

2

Dynamic attribute access in Python is provided with the built-in function getattr:

>>> getattr(x, list_[1])
'2'
>>> [getattr(x, name) for name in list_]
['1', '2']
wim
  • 338,267
  • 99
  • 616
  • 750
1

If you are trying to access object properties by their name, try this:

list = ['one', 'two']
print getattr(x, list[1])
bosnjak
  • 8,424
  • 2
  • 21
  • 47
1

You want the getattr function:

getattr(x, list[1])
Alex Hall
  • 34,833
  • 5
  • 57
  • 89