How to set attribute with index in the name in python

80 Views Asked by At

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.

0

There are 0 best solutions below