Python: Create 50 Objects Using a for Loop

Python: Create 50 objects using a for loop

You can do this like so:

class foo():
def __init__(self,name):
self.name = name

def __str__(self):
return name

def __repr__(self): # will print the "name" as repres of this obj
return self.name

objects= [foo(str(i)) for i in range(1,51)] # create 50 foo-objects named 1 to 50

print(objects) # list that contains your 50 objects

Output:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 
25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45,
46, 47, 48, 49, 50]

If you remove the def __repr__() you get smth like:

[<__main__.foo object at 0x7fd4e9b78400>, 
<__main__.foo object at 0x7fd4e9b78470>,
... etc ...,
<__main__.foo object at 0x7fd4e9afd940>,
<__main__.foo object at 0x7fd4e9afd9b0>]

How to create multiple class objects with a loop in python?

This question is asked every day in some variation. The answer is: keep your data out of your variable names, and this is the obligatory blog post.

In this case, why not make a list of objs?

objs = [MyClass() for i in range(10)]
for obj in objs:
other_object.add(obj)

objs[0].do_sth()

create multiple objects in a for loop

There is nothing special about models, they are objects so you can create a list of Model objects (regressors) in a loop:

regressors = list()
for _ in range(20):
model = Sequential()
model.add(LSTM(units=50, ...))
model.add(Dropout(0.2))
regressors.append(model)
# Now access like you would any array
# regressors[0] etc will give you models.

How to create objects and then apply methods to them in a loop

You can use a list comprehension and iterate over your parameters to create all the instances of Sprite.

from itertools import product

x_coords = [250, 350, 450]
y_coords = [200, 300, 400]

boards = [classes.sprite.Sprite(x=x, y=y) for x, y in product(x_coords, y_coords)]

for board in boards:
board.set_image('board.png')

board_0 thus becomes boards[0]. Using itertools.product is just short for writing out the x,y pairs you have in your example.

How to manually add objects to a Django model using a for loop?

It is about Python not Django. Simply you can't do this in Python

class MyAwesomeClass:
a = 1
print(a)
print(MyAwesomeClass.a)

this will throw throw NameError on 4. line

Instead use shell to create data like so
python manage.py shell

from yourapp.models import UserLevel
UserLevel.objects.bulk_create([UserLevel(level_rank=level) for level in range(1, 101)])


Related Topics



Leave a reply



Submit