简体   繁体   中英

How do I create dynamically, and manage, new instances of common data types in Python?

I want to make a program which will ask the user for a number (let's say 3) and create three 3x3 lists, or 3 sets of 3 members or some other complex data type (times 3) Python already knows of.

Many programs create new objects without strict programming declaration of their instances. For example in Cinema4D (3D graphics software) i can push a button and create as many cubes I want. But I don't know the programming mechanics of this automatic instance creation without a written code declaration like:

cubeobj cube_1  
cube_1.name("Cube.1") ...

In C++ something like that would require the operator new and the function malloc() . Are there any equivalents for them in Python?

I've searched among many Python books and didn't find anything, what kind of Python topic would discuss something like that?

try this:

num = input()
lst = [[0 for __ in range(num)] for _ in range(num)]

for specific type you should use numpy arrays or array module

If you want a triple nested list, you can create it like this:

In [1]: num = 3

In [2]: [[[[0 for __ in range(num)] for _ in range(num)]] for ___ in range(num)]
Out[2]: 
[[[[0, 0, 0], [0, 0, 0], [0, 0, 0]]],
 [[[0, 0, 0], [0, 0, 0], [0, 0, 0]]],
 [[[0, 0, 0], [0, 0, 0], [0, 0, 0]]]]

Managing multidimensional arrays may be much easier with numpy though:

In [3]: import numpy as np

In [4]: np.zeros((num, num, num))
Out[4]: 
array([[[ 0.,  0.,  0.],
        [ 0.,  0.,  0.],
        [ 0.,  0.,  0.]],

       [[ 0.,  0.,  0.],
        [ 0.,  0.,  0.],
        [ 0.,  0.,  0.]],

       [[ 0.,  0.,  0.],
        [ 0.,  0.,  0.],
        [ 0.,  0.,  0.]]])

But the answer to your question in general is just that - you can create as many objects as you like by calling the corresponding constructor and keeping the returned instance accessible through a list, a dictionary or something else.

Using a hypothetical cube example, you can create num Cube objects and put them all in a list:

num = int(input())
cubes = [Cube(name="Cube " + str(i)) for i in range(num)]

OK, I think I've come up with a solution. Instead of trying to find a way to create new lists I will just append as many new indexes I need on a predefined empty list and treat that linear list as many unrelated lists using for loops and modulos related to my input number.

I still don't know a generic programming method for automatic class instancing though ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM