直接从函数调用获取属性。Python3.x

直接从函数调用获取属性。Python3.x,python,function,class,python-3.x,attributes,Python,Function,Class,Python 3.x,Attributes,我在这里编写了示例代码,只是为了说明我想做什么: 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

我在这里编写了示例代码,只是为了说明我想做什么:

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

我只想知道它是否可行,以及如何实现?我不知道我是否在尝试做一些不正确的事情,但如果可以做到这一点,对我来说将是一个很好的解决方案。也许可以尝试引导我找到可以解释的正确文本?

您可以使用以下方法动态访问属性:

因此,
example函数
中的行是:

print(getattr(listex[randomnumber], myproblem))

对不起,你的问题不清楚。对于
print(listex[randomnumer].myproblem)
,您希望它打印listex[randomnumer].example所做的class属性。这就是您上一行所做的。你想打印名字吗?或者您想动态打印
listex[randomnumber]
上的所有可用属性吗?我制作了这个示例代码,这样就不需要复制我正在处理的代码。这是为了一项作业,我不想让它被困在检查剽窃的系统中。原因是我有几个属性,根据我在函数中调用的内容,我希望打印出正确的属性,而不必写say.example,这不是问题。这里的问题是,你的问题相当模糊。好的,这是可行的。这个网站的社区给人的第一印象很好。干杯不客气!如果答案解决了你的问题,请记住将该问题标记为已解决:)
print(getattr(listex[randomnumber], myproblem))