我在这里制作了示例代码只是为了展示我想要完成的任务:
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
我只需知道它是否可行而且大致如何?不知道我是否正在尝试做一些不正确的事情,但如果能做到这一点对我来说将是一个很好的解决方案。也许试着引导我找到可以解释的正确文本?
答案 0 :(得分:1)
您可以使用getattr
动态访问属性:
class myclass:
def __init__ (self, example):
self.example = example
x = myclass('foo')
print(getattr(x, 'example')) # foo
所以examplefunction
中的行就是这样:
print(getattr(listex[randomnumber], myproblem))