0

I'm trying to setattr() using name list. When calling it the names containing index number in square brackets raises AttributeError in Python 2 and TypeError in Python.

class NodeClass():
def __init__(self):
    self.name = "NodeName"
    self.set()
    
def set(self):
    for i in ["worldMatrix", "worldMatrix[0]", "worldMatrix[1]"]:
        attr_dict = {"attribute": i}
        setattr(self, i, AttrClass(self.name, **attr_dict))

class AttrClass():
    def __init__(self, node, **kwargs):
        self.att = kwargs.get("attribute")
        self.node = node
    
    def set_matrix(self, matrix=None):
        if not matrix:
            matrix = [1.0, 0.0, 0.0, 0.0, 
                      0.0, 1.0, 0.0, 0.0, 
                      0.0, 0.0, 1.0, 0.0, 
                      0.0, 0.0, 0.0, 1.0]
        return self.node, self.att, matrix

obj = NodeClass()
obj.worldMatrix.set_matrix()  
obj.worldMatrix[0].set_matrix() # this causes error

Python 2: # AttributeError: AttrClass instance has no attribute '__getitem__' #

Python 3: # TypeError: 'AttrClass' object is not subscriptable #

I deduce that I need somehow implement __getitem__() but don't know how.

IKA
  • 151
  • 1
  • 3
  • 11
  • 1
    You need to implement `__getitem__`, not `__getattr__`, just as the error message suggests. – chepner Apr 26 '23 at 20:49
  • 1
    `obj.worldMatrix[0]` is equivalent to `obj.worldMatrix.__getitem__(0)`. – chepner Apr 26 '23 at 20:50
  • 1
    I very much doubt you want to create an attribute named `worldMatrix[0]` in `NodeClass.set`. `obj.worldMatrix[0] = ...` is equivalent to `setattr(obj.worldMatrix, 0, ...)`, not `setattr(obj, 'worldMatrix[0]', ...)`. – chepner Apr 26 '23 at 20:50
  • Ok. I have implemented `__getitem__` and now I get what I originally needed - index number. Thank you for your help. – IKA Apr 27 '23 at 10:28

0 Answers0