0

I've made and example code here just to show what I want to get done:

import random
class myclass:
    def __init__(self,example):
        self.example=example


listexample = ["1","2","3","4","5"]

objlist = []
for i in listexample:

    objlist.append(myclass(i))


#Ok so here I got a list of objects



def examplefunction(listex, myproblem):


    randomnumber = random.randrange(0,5)
    print(listex[randomnumber].example)    # This works, of course
    print(listex[randomnumber].myproblem) # here, myproblem should be "example" and print one of my numbers.


examplefunction(objlist,"example")   # here.. I want this to get the attribute of the class

I just need to know if it is doable and approximately how? Don't know if I'm trying to do something that just isn't right but if this could be done it would be a good solution for me. Maybe try to guide me to the right piece of text which can explain?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Boidae
  • 3
  • 2
  • Sorry, your question is not clear. What do you to happen for `print(listex[randomnumber].myproblem)`? – Martijn Pieters Dec 21 '13 at 14:44
  • I want it to print the class attribute that listex[randomnumer].example does. – Boidae Dec 21 '13 at 14:47
  • That is what your previous line does. Did you want to print the *name*? Or did you want to print *all* attributes available on `listex[randomnumber]`, dynamically? – Martijn Pieters Dec 21 '13 at 14:48
  • I made this example code so that I wouldn't need to copy the code I am working on. It's for an assignment and I don't want it to get stuck in the system that checks for plagiarism. The reason is that I have several attributes and depending on what I call in the function I want the proper attribute to be printed without having to write say .example after it – Boidae Dec 21 '13 at 14:50
  • That is not a problem. What is at issue here is that your question is rather vague. – Martijn Pieters Dec 21 '13 at 14:51
  • @delnan: you read it better than I did. – Martijn Pieters Dec 21 '13 at 14:53
  • It's vague because I don't know the right terminology I think. Thanks a bunch though! – Boidae Dec 21 '13 at 14:57

1 Answers1

1

You can access a property dynamically using getattr:

class myclass:
    def __init__ (self, example):
        self.example = example

x = myclass('foo')
print(getattr(x, 'example')) # foo

So the line in your examplefunction would be this:

print(getattr(listex[randomnumber], myproblem))
poke
  • 369,085
  • 72
  • 557
  • 602