1

I would like to generate a list made up of the attributes of some objects (arbitrarily) and that the changes made to the list change the object and vice versa. For example:

class objeto():    
    def __init__(self):
        self.attr1 = 1
        self.attr2 = 2
 
obj1 = objeto()
obj2 = objeto()

lista = [obj1.attr1, obj2.attr2]

obj1.attr1[0] = 4

# I would like to see [4, 2]
print(lista)

I know that numbers are immutable but I am wondering if there is any way to do it without using lists.

  • 2
    What are you trying to achieve by such a feature? I don't think this will be easily possible, but maybe there is a better way for what you actually want to do. – mkrieger1 Aug 18 '20 at 15:24
  • 2
    Instead of single-element lists, write a `Property` class (classes should be capitalized) and set/get the field on that object. Then your `Objecto` will simply have references to objects which lets them be mutated in multiple places. But this is likely a terrible solution to whatever problem you're facing, and if you explain the underlying scenario this is supposed to help with, we can offer a better solution. See [xy problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) – ggorlen Aug 18 '20 at 15:28
  • Not quite clear what you want or why you want it. You could create a class of list-like objects which function as containers for mutable objects and use `__getitem__` so that it just shows the target attribute of the contained objects and `__setitem__` so that it mutates the contained objects. Such a thing could be thought of as providing a view of the contained objects (with perhaps the viewed attribute being set by `__init__`). This approach wouldn't work for containers of immutable objects. – John Coleman Aug 18 '20 at 15:37
  • `lista` initially contains `[[1], [2]]`, not `[1, 2]`. Your assignment should change it to `[[4], [2]]`, which seems to be what you want. – Barmar Aug 18 '20 at 15:42

0 Answers0