0

I'm trying to create some simple objects that are defined dynamically through a class - to allow me to rapidly iterate through the creation of all possibilities of these objects.

class NSObjects:
    def __init__(self, shape, position, shading):
        self.shape = shape
        self.position = position
        self.shading = shading

    def __str__(self):
        return '{} - {} - {}'.format(self.shape(), self.position(), self.shading())


def NSGenerator_1():
    for i in range (0,3):
        obj_1_i = NSObjects(shape_init_top + i, posn_init_top+i, shading_init_top+i)

    for i in range (3,6):
        obj_1_i = NSObjects(shape_init_mid + i, posn_init_mid+i, shading_init_mid+i)

    for i in range (6,9):
        obj_1_i = NSObjects(shape_init_mid + i, posn_init_mid+i, shading_init_mid+i)

NSGenerator_1()
print(obj_1_2)

At the moment it is telling me that obj_1_2 doesn't exist. For the purpose of this you can assume that I have defined all the init variables to start at 0, 1 or 2 elsewhere in the code. I am basically trying to create a series of objects which will have properties as defined by a mathematical formula.

Thanks in advance for any help you can provide (I only started coding a few weeks ago so this might be a very silly question!)

1 Answer 1

2

You only ever assigned to obj_1_i, not obj_1_2, and it was local to the function. There is no way for Python to tell that the _i was meant as a separate variable instead of part of the longer variable name. For a quick fix, try replacing the obj_1_i = parts with globals()[f'obj_1_{i}'] =.


But rolling numeric indexes into the variable names like that (_1_2) is a code smell. A better design is to actually use them as indexes to a data structure, like a list or dict.

For example, define obj = {} at the top level (outside of any class or function).

Then you can replace obj_1_2 everywhere with obj[1, 2], etc. If you wrote them that way,
obj[1, i] would work as you expect inside those for loops.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! This makes perfect sense - I need all the style tips I can get!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.