Python类实例返回值

问题描述:

我的问题如下:我有一个类Taskpane与几个方法。实例化按其应有的方式工作。现在,当我显示所有实例化对象的列表时,我想打印出每个对象的成员变量,例如_tp_nr。Python类实例返回值

以下代码返回正确的值,但它以奇怪的(?)格式返回。

这是代码:

#import weakref 

class Taskpane(): 
    '''Taskpane class to hold all catalog taskpanes ''' 

    #'private' variables 
    _tp_nr = '' 
    _tp_title = '' 
    _tp_component_name = '' 

    #Static list for class instantiations 
    _instances = [] 

    #Constructor 
    def __init__(self, 
        nr, 
        title, 
        component_name): 

     self._tp_nr    = nr, 
     self._tp_title   = title, 
     self._tp_component_name = component_name 

     #self.__class__._instances.append(weakref.proxy(self)) 
     self._instances.append(self) 

    def __str__(self): 
     return str(self._tp_nr)  

    def setTaskpaneId(self, value): 
     self._tp_nr = value 

    def getTaskpaneId(self): 
     return str(self._tp_nr) 

    def setTaskpaneTitle(self, value): 
     self._tp_title = value 

    def getTaskpaneTitle(self): 
     return str(self._tp_title) 

    def setTaskpaneComponentName(self, value): 
     self._tp_component_name = value 

    def getTaskpaneComponentName(self): 
     return self._tp_component_name 

tp1 = Taskpane('0', 'Title0', 'Component0') 
tp2 = Taskpane('1', 'Title1', 'Component1') 

#print Taskpane._instances 

#print tp1 

for instance in Taskpane._instances: 
    print(instance.getTaskpaneId()) 

for instance in Taskpane._instances: 
    print(instance.getTaskpaneTitle()) 

结果:

('0',) 
('1',) 

('Title0',) 
('Title1',) 

的问题是:为什么 它返回在这种格式的结果吗?我希望只看到:

'0' 
'1' 

('Title0') 
('Title1') 

使用:

for instance in Taskpane._instances: 
    print(instance._tp_nr) 

的结果是一样的。

+1

你只有一些语法问题,所以你的回答不会帮助别人(因此我downvote)。 – Alfe

+0

@Alfe除了知道这可能是一个问题... – glglgl

+0

是的,但是在任何情况下都是随机发现。如果标题像“为什么不用这些尾随逗号工作”,一切都会好起来的。 – Alfe

删除尾部逗号,将值转换为元组。

+0

谢谢你的帮助。看起来像一个经典的错误。 –

在该串中的构造的末尾删除逗号:

self._tp_id    = nr, 
self._tp_title   = title, 

Python的对待,表达式作为元组与一个元件

+1

这太可怕了。我的错误: - $谢谢。 –

您正在通过使用逗号创建的元组:

self._tp_id    = nr, 

逗号是什么使得_tp_id成为一个元组:

>>> 1, 
(1,) 
+0

谢谢你的帮助 –