繁体   English   中英

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

[英]Can I use class attributes as function argument in 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)

我认为您正在寻找的是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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM