I have a class with an attribute. Originally it held a single string of an error message. I thought I would get clever and turn it into a list so every time I 'set' the attribute, rather than replacing the string it would append the string to a list.
Now, however, the err
attribute is shared amongst the objects rather than being unique for each one.
Here is my code (test.py
, trimmed to just the minimum for this example)
#!/usr/bin/python3
# pylint: disable=C0301
'''Testing MyHost class'''
class MyHostGood: # pylint: disable=R0903
'''Host class'''
err = ''
name = ''
def __init__(self, name=''):
'''Constructor'''
self.name = name
def __str__(self):
'''Return a printable user representation of the object - print(x)'''
info = f'{self.name}:'
# These are error/warning messages
if self.err:
info += f'\n└ ERROR: {self.err}'
return info
class MyHostBad: # pylint: disable=R0903
'''Host class'''
_err = []
name = ''
def __init__(self, name=''):
'''Constructor'''
self.name = name
def __str__(self):
'''Return a printable user representation of the object - print(x)'''
info = f'{self.name}:'
# These are error/warning messages
if self._err:
for errMsg in self._err:
info += f'\n└ ERROR: {errMsg}'
return info
@property
def err(self):
'''Return the list of error messages'''
return self._err
@err.setter
def err(self, arg):
'''Add another string to the error messages'''
if isinstance(arg, str):
self._err.append(arg)
if isinstance(arg, list):
self._err.extend(arg)
Here is the good class where the err
attribute is unique:
>>> import test
>>> a = test.MyHostGood('foo')
>>> a.err = 'Here is one error string'
>>> print(a)
foo:
└ ERROR: Here is one error string
>>> b = test.MyHostGood('bar')
>>> print(b)
bar:
>>> b.err = 'a new error'
>>> print(a)
foo:
└ ERROR: Here is one error string
>>> print(b)
bar:
└ ERROR: a new error
>>>
And here the err
attribute is now shared between the objects:
>>> import test
>>> c = test.MyHostBad('wiz')
>>> c.err = 'Here is one error string'
>>> print(c)
wiz:
└ ERROR: Here is one error string
>>> d = test.MyHostBad('baz')
>>> print(d)
baz:
└ ERROR: Here is one error string
>>> d.err = 'a new error'
>>> print(c)
wiz:
└ ERROR: Here is one error string
└ ERROR: a new error
>>> print(d)
baz:
└ ERROR: Here is one error string
└ ERROR: a new error
>>>
How do I fix the getter/setter so the objects have their own error strings again?