Issue
How to create a list of a specific type of object but empty? Is it possible? I want to create an array of objects (the type is called Ghosts) which later will contain different types that inherit from that one class called Ghosts. It's all very simple in C++ but i'm not sure how to do that in python. I tried something like this:
self.arrayOfGhosts = [[Ghost() for x in xrange(100)] for x in xrange(100)]
but it's already initialised by objects, and I don't need it, is there a way to initialise it by 0 but have an list of type Ghost?
As you see I'm very new to python. Any help will be highly appreciated.
Solution
Those are lists, not arrays. Python is a duck-typed language. Lists are heterogenously-typed anyway. For example. your list can contain an int
, followed by str
, followed by list
, or whatever suits your fancy. You cannot restrict the type with stock classes, and that's against the philosophy of the language.
Just create an empty list, and add later.
self.arrayOfGhosts = []
Two-dimensional lists are simple. Just nest lists.
l = [[1, 2, 3], [4, 5, 6]]
l[0] # [1, 2, 3]
l[1][2] # 6
If you really want placeholders, just do something like the following.
[[None] * 100 for i in range(100)]
Python doesn't have arrays, unless you mean array.array
, which is for C-ish types anyways. Arrays are the wrong level of abstraction in Python most of the time.
P.S. If you're using xrange
, then you must be using Python 2. Unless you need very specific libraries, please stop, and use Python 3. See why.
P.P.S. You initialize with NULL
, not 0
in C++. Never use 0
to mean NULL
.
P.P.P.S. See PEP 8, the canonical Python style guide.
Answered By - pilona
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.