我可以在python中使用类属性作为函数参数吗?

时间:2017-05-19 03:14:05

标签: python class attributes

我想做像

这样的事情
class myclass(object):
    def __init__(self, arg1, arg2, arg3):
        self.arg1 = arg1
        self.arg2 = arg2
        self.arg3 = arg3

    def printattribute(self, arg):
        print(self.arg)

a = myclass(1,2,3)
a.printattribute(arg2)

并打印a.arg2的值,但我不断获得a do not have arg attribute。如何使python理解并在点符号后更改arg,以便像这样的事情

def createlist(self, flag):
    myset = set()
    if flag == 'size':
        for myfile in self.group:
            myset.add(myfile.size)
    if flag == 'head':
        for myfile in self.group:
            myset.add(myfile.head)
    if flag == 'tail':
        for myfile in self.group:
            myset.add(myfile.tail)
    if flag == 'hash':
        for myfile in self.group:
            myset.add(myfile.hash)
    return sorted(myset)

变成

def createlist(self, flag):
    myset = set()
    for myfile in self.group:
        myset.add(myfile.flag)
    return sorted(myset)

1 个答案:

答案 0 :(得分:0)

我认为您要找的是getattr

 def printattribute(self, arg):
        print(getattr(self,arg))

调用它你将使用类似的东西:

a.printattribute('arg2')

你的最终功能可能如下所示:

def createlist(self, flag):
    myset = set()
    for myfile in self.group:
        myset.add(getattr(myfile, flag))
    return sorted(myset)