My problem is as follows: I have a class Taskpane with a couple of methods. Instantiating works as it should. Now, when i show a list of all instantiated objects, i would like to print out a member variable per object for example the _tp_nr.
The following code returns the correct values, but it gets return in a strange(?) format.
This is the code:
#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() )
Result:
('0',)
('1',)
('Title0',)
('Title1',)
The question is: Why does it return the results in this kind of formatting? I would expect only to see:
'0'
'1'
('Title0')
('Title1')
When using:
for instance in Taskpane._instances:
print( instance._tp_nr )
The result is the same.
You are creating tuples by using a comma:
self._tp_id = nr,
The comma is what makes _tp_id
a tuple:
>>> 1,
(1,)
Remove commas in the end of this strings in constructor:
self._tp_id = nr,
self._tp_title = title,
Python treats such expressions as tuple with one element
删除尾随逗号,这些逗号将值转换为元组。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.