0

I was trying to create multiple data members for a class in python uisng the for loop but seems like python creates just a single data member for each loop iteration. I am sure the way am doing it is correct or not but if any of you get my motive and can help then please do. I think setitem could be a solution but i don't know how?

class VectorNd:
    def __init__(self,**kwargs):
        self.length = 0
        self.member_names = kwargs.keys()
        for (i,j) in kwargs.items():
            self.i = j
    
    def __str__(self):
        ret_str = ''
        print(self.member_names)
        for i in self.member_names:
            ret_str += f'({self.i}{i}) +'
        return ret_str[:-2]

obj = VectorNd(i=1,j=2,k=3,l=5)
print(obj.i)

Output: 5

I wish to create new data members each time the loop is iterated instead of creating a single self.i data member.

2
  • self.i = j => setattr(self, i, j). Otherwise, you just set the same attribute i all over again. Likely, in __str__ it should be getattr(self, i) Commented Apr 5, 2022 at 3:26
  • You can just use vars(self).update(kwargs) here. Commented Apr 5, 2022 at 3:28

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.