0

I have a class file:

class Land:
 id = None
 blocks = []

class Block:
 blockId = None
 blockName = None

I am going through a long list of json data and creating land with blocks inside it. The code is similar to:

for value in jsonList:
  l = Land()
  l.id = value.id
  
  for block in value.blocks:
    b = Block()
    blockId = block.id
    blockName = block.name
    l.blocks.append(b)

when I later look at this, every land item in the array, has EVERY block added, so it doesn't seem to be creating new instances of the Land.blocks list when I create a new land object, it's referencing the previous one.

What am I doing wrong here? (I'm used to the new keyword in C# and clearly missing reference or something?)

Edit:

I think based on the comments below I need to do?:

class Land:  
    def __init__(self):   
        self.id = None   
        self.Blocks = []   
  
class Block:  
    def __init__(self):   
        self.blockId = None  
        self.blockName = None
  • Ignoring the typo `def` for `class`, your classes don't create any *instance* attributes, only *class* attributes shared by all instances. See https://docs.python.org/3/tutorial/classes.html. – chepner Jun 08 '23 at 19:37
  • You also never assign to `b.blockID` or `b.blockName`; you are assigning to otherwise unused local variables instead. – chepner Jun 08 '23 at 19:43
  • thank you, edited that typo to fix the class vs def line – Jason Orman Jun 08 '23 at 19:45
  • shouldn't b = Block() create a new instance of the class akin to the new keyword in other languages? – Jason Orman Jun 08 '23 at 19:49
  • It does, but ever block is added to the same shared *class* attribute `blocks` shared by every instance of `Land`. Each instance of `Land` needs its *own* instance attribute `blocks`. Please read the linked tutorial section to learn the different between class and instance attributes, and how to properly initialize an instance. (You should be defining an `__init__` method for each class to define the instance attributes, not creating the attributes manually after the fact.) – chepner Jun 08 '23 at 19:53
  • Ok, I think I'm understanding better what you mean here, I'm reading through the link you sent over and updated the initial question with what I think makes sense now based on the page you sent over (instance vs reference to the class variable) – Jason Orman Jun 08 '23 at 20:02
  • Close. If you are going to do, for example, `l = Land(); l.id = value.id`, then define `Land.__init__` so that you can write `l = Land(value.id)` instead. – chepner Jun 08 '23 at 20:16

0 Answers0