Jul-22-2021, 11:00 AM
(Jul-21-2021, 07:36 PM)deanhystad Wrote: This is what you are trying to do:Thank you very much
class MyClass: def __init__(self, alist): self.alist = alist def func(self, list_arg): list_arg= ['a', 'new', 'list'] def __str__(self): return str(self.alist) obj = MyClass(['This', 'is', 'a', 'list']) print(obj) obj.func(obj.alist) print(obj)Setting the value of list_arg in func() does nothing to alist because alist and list_arg are not the same variable. They reference the same list object (initially), but they are not the same variable. Changing one does not affect the other.
Output:['This', 'is', 'a', 'list'] ['This', 'is', 'a', 'list']
If you really need your listread() method to change the xlist variable you could pass the attribute name and use that to set the xlist attribute.
class MyClass: def __init__(self, alist): self.alist = alist def func(self, list_attr): self.__setattr__(list_attr, ['a', 'new', 'list']) # Set attribute using the attribute name def __str__(self): return str(self.alist) obj = MyClass(['This', 'is', 'a', 'list']) print(obj) obj.func('alist') # Pass the attribute name print(obj)I can't say how much I think this is a bad idea, but it can be done. Lucky for you, you don't have to resort to such ugly code. You don't really have any reason to change the list variable. You are really only interested in what the list contains.
Output:['This', 'is', 'a', 'list'] ['a', 'new', 'list']
class MyClass: def __init__(self, alist): self.alist = alist def func(self, list_arg): list_arg[:] = ['a', 'new', 'list'] # Modify the list, don't make a new list def __str__(self): return str(self.alist) obj = MyClass(['This', 'is', 'a', 'list']) print(obj) obj.func(obj.alist) print(obj)This code works because we are changing the list object, not the instance variable that references the list object. It can be confusing at first, but variables are not the thing they reference. This can be shown with a simple example:
Output:['This', 'is', 'a', 'list'] ['a', 'new', 'list']
a = ['a', 'list'] b = a print(a, b) b = 12 print(a, b)Changing "b" did nothing to "a". The list that "a" references is unchanged even though the variable "b", which referenced the same list, has changed.
Output:['a', 'list'] ['a', 'list'] ['a', 'list'] 12
Because lists are mutable (can be changed), you can make it look like changing "b" changes "a".
a = ['a', 'list'] b = a print(a, b) b[:] = ['different', 'contents'] print(a, b)It looks like changing "b" changed the value of "a", but this is not correct. The value of "b" never changed. Instead we changed the list object that is referenced by "b" (and "a"). Since a and b are both looking at the same list, any changes to that list are seen when you reference the list through "a" or "b".
Output:['a', 'list'] ['a', 'list'] ['different', 'contents'] ['different', 'contents']