Python:通过变量名访问实例的方法?

时间:2015-04-06 03:57:11

标签: python class methods instance

这里有一个python初学者。对不起,如果这个问题很愚蠢。我只是想尝试访问一个实例类'方法(addComponentToIC)通过"变量"从字典中读入的对象/实例名称。

我创建了一个如下所示的字典:

qaDict = {} # a place to store the DSIDs/names for later use

jd = r.findDSIDs('My QA Team', 'External') # make the call to get unique IDs

for a in jd:

(a['lastName']).lower() + '_' + (a['firstName']).lower() #name the object   using "last_name_firstName"
if a['dsid'] not in blacklistedDSIDs:
    globals()[qaperson] = Ic(a['dsid'], a['lastName'], a['firstName']) ## create the Ic object
    qaDict[a['dsid']] = qaperson  ## add person to list of DSIDs

然后我想获取这些ID并获取他们验证者的所有组件:

for key, value in qaDict.items():

    jd = r.findComponents(key)  
    getattr(value, 'addComponentToIC')(jd['id'], jd['name'])

我得到了:AttributeError: 'unicode' object has no attribute 'addComponentToIC'

我也尝试过:

for key, value in qaDict.items():

    jd = r.findComponents(key)  
    value.addComponentToIC(jd['id'], jd['name'])

这也会引发同样的错误。所以它似乎与变量名称"值"有关,实际上并没有被解释为实例名称。它应该看起来像:

employees_name.addComponentToIC(jd['id'], jd['name']) 

- 其中" employees_name"是先前创建的类的实例,但它不起作用。我知道这里有一些傻事我不理解;-)非常感谢任何帮助!

My Class看起来像这样:

class Ic(object):

    'This is a class for QA folks'

    empCount = 0

    @classmethod
    def displayEmployeeCount(class_obj):
        print ("The total employee count is %d" % Ic.empCount)

    def __string__(self):
        return str(self)

    def __init__(self, dsid, fname, lname):

        self.dsid = dsid
        self.fname = fname
        self.lname = lname
        self.name = fname + ' ' + lname
        Ic.empCount += 1
        self.ticketCount = 0
        self.componentCount = 0
        self.componentDict = {}
        self.componentName = ''
        #Ic.instances.add(self)

    def addComponentToIC(self, componentID, componentName):
        self.componentName = componentName
        self.componentID = componentID
        self.componentDict[componentID] = componentName

    @classmethod
    def get_instances(cls):
        return list(Ic.instances)

    def addTicketCount(self, count):
        self.ticketCount += count

    def addComponentCount(self, count):
        self.componentCount += count

    def displayComponentNumber(self):
        print (self.name, " has ", len(self.componentDict), " number of components.")

    def displayEmployee(self):
        print ("Name: ", self.name, "DSID: ", self.dsid, "Count: ", self.ticketCount, ", Component Count: ", len(self.componentDict))

    def displayComponentDict(self):
        print ("This employee is verifier for the following components: ", self.componentDict)

2 个答案:

答案 0 :(得分:0)

qaperson将始终指向unicode对象。要访问指向qaperson的全局名称的值,您必须通过globals()访问它。以下是正在发生的事情的一个例子。

>>> class Foo(object):
    def __init__(self, n):
        self.n = n
    def bar(self):
        print self.n, 'bar!'

>>> x = 'k'
>>> globals()[x] = Foo(x)
>>> x
'k'
>>> x.bar()

Traceback (most recent call last):
  File "<pyshell#38>", line 1, in <module>
    x.bar()
AttributeError: 'str' object has no attribute 'bar'
>>> k
<__main__.Foo object at 0x03FD02F0>
>>> k.bar()
k bar!
>>> globals()[x]
<__main__.Foo object at 0x03FD02F0>
>>> globals()[x].bar()
k bar!
>>> 
>>> d = {1:x}
>>> d
{1: 'k'}
>>> d[1].bar()

Traceback (most recent call last):
  File "<pyshell#45>", line 1, in <module>
    d[1].bar()
AttributeError: 'str' object has no attribute 'bar'
>>> globals()[d[1]]
<__main__.Foo object at 0x03FD02F0>
>>> globals()[d[1]].bar()
k bar!
>>>

也许您应该只使用IC实例来qaDict值:

if a['dsid'] not in blacklistedDSIDs:
    ic = Ic(a['dsid'], a['lastName'], a['firstName']) ## create the Ic object
    globals()[qaperson] = ic
    qaDict[a['dsid']] = ic  ## add person to list of DSIDs
    # or
    #qaDict[ic.dsid] = ic

然后使用我的例子,你会像这样使用它

>>> x = 'k'
>>> f = Foo(x)
>>> d = dict()
>>> d[f.n] = f
>>> d
{'k': <__main__.Foo object at 0x03FC2A70>}
>>> for k,v in d.items():
    print k
    v.bar()

k
k bar!
>>> 

答案 1 :(得分:0)

我解决了这个问题 - 感谢所有人的帮助。我试图弄清楚如何选择&#34;第二次世界大战的答案,但它不会让我赞成它。这个网站也很难为我找到 - 不仅仅是python。

无论如何,这是我最终的工作:

objs = []
for a in jd:

    fullname = (a['lastName']).lower() + '_' + (a['firstName']).lower() #name the object using "last_name_firstName"

    if a['dsid'] not in blacklistedDSIDs:

        x = Ic(fullname, a['dsid'])
        objs.append(x)

for employee in objs:
    employee.addTicketCount(5)

for employee in objs:
    employee.displayEmployee()