Python Forum
Init an indefinite number of class
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Init an indefinite number of class
#10
Quote:Wouldn't this be easier players = [Player()] * x
Nope. If you do this you end up with 1 player. players[0] would be the same player as players[1] and so on. This is a common problem where programmers try to create a list of mutable objects using the "*" operator.

Nobody complains if "numbers = [0] * count" returns a list where numbers[0] is numbers[1], but it is usually not the desired result when trying to make a list of lists. "lists = [[]] * count" works exactly the same as "numbers", where lists[0] is lists[1]. In both cases you have a list holding a single value that is used to create a list holding multiple of the value. if you want a different value for each item in the list you need a different generator.

To make a list containing different numbers you might do this
numbers = [number for number in range(count)]
To build a list of different lists you do this:
lists = [[] for _ in range(count)] 
And to build a list of different players you do this:
players = [Player() for _ in count]
Reply


Messages In This Thread
RE: Init an indefinite number of class - by deanhystad - Feb-18-2022, 07:49 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Which GUI can have indefinite loop ? jst 20 1,770 Nov-16-2023, 10:23 PM
Last Post: jst
  PyRun_SimpleFile calling multiprocessing Python Class cause endless init loop Xeno 2 1,056 Sep-19-2022, 02:32 AM
Last Post: Xeno
  Basic Inheritance, Why Use init udinjelek 5 2,190 Sep-29-2021, 06:03 PM
Last Post: deanhystad
  Indefinite loop ( I think ) marsh20 2 1,935 Aug-20-2020, 12:33 PM
Last Post: deanhystad
  Error: How to to close and restart your shell after running 'conda init' angelica 3 10,283 May-27-2020, 10:00 AM
Last Post: snippsat
  Is it mandatory to call superclass init inside the class init? psolar 3 6,069 Feb-14-2020, 09:16 PM
Last Post: wavic
  indefinite loop Johnygo 3 2,148 Jul-03-2019, 12:53 PM
Last Post: Johnygo
  init vs_init_ while defining method/function? hsunteik 1 3,657 Dec-24-2016, 08:27 AM
Last Post: micseydel

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020