-4

Within pytorch, creating layers, can be semi automated, thus the reason for using a for loop.

One of the main issues is that these layers cannot stored within a list or dictionary or else back propagation will not work.

Thus the reason for a work around.

Within the object, assigning new self attributes

How do i replace this

self.res1 = 1
self.res2 = 2
self.res3 = 3

with this

for i in range(2):
  res_name = 'res'+str(i+1)
  self.res_name = i

Now that i have created objects this way, how can I access them in the same way. For example, if we assume self.res_name is now an object?

for i in range(2):
   res_name = 'res'+str(i+1)
   out = self.res_name(out)
MadmanLee
  • 478
  • 1
  • 5
  • 18

1 Answers1

1

You probably should use a dict or list instead. But if you really want this for some reason, you can try setattr(x, attr, 'magic').

Thus, in your case, it's

for i in range(1, 4):
    res_name = 'res' + str(i)
    setattr(self, res_name, i)

See this related question for more info.

hiiwave
  • 40
  • 3