2017-05-19 151 views
0

我想這樣做我可以在Python中使用類屬性作爲函數參數嗎?

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) 

回答

0

我想你正在尋找的是getattr

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

來稱呼它,你會使用類似的東西:

a.printattribute('arg2') 
您的最終功能可能看起來像這樣:
相關問題