-1

In this example code, I am creating 100 objects in a list with random x values, but the problem is that all of the created objects have the same x value. I tried searching web for solutions for this but I couldn't find any.

import random
list = []
class object:
    x = random.randint(1,1000)

for i in range(1,101):
    list.append(object())

for i in range(1,100):
    print(list[i].x)
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Franek
  • 3
  • 1
  • 4
    1. You're shadowing the built-in object; and 2. you only pick a random number *once*. You shouldn't do either of those things. – jonrsharpe Feb 15 '20 at 20:53
  • 4
    You're using a class variable instead of an instance variable. You should be doing: `class A: def __init__(self): self.x = random.randint(1, 1000)` – rassar Feb 15 '20 at 20:54
  • 1
    You're also shadowing the built-in `list` – wjandrea Feb 15 '20 at 21:07

1 Answers1

1

Read up on Class and Instance Variables in the Python Docs to get clarification on your specific confusion.

Generally speaking, instance variables are for data unique to each instance and class variables are for attributes and methods shared by all instances of the class:

class Dog:

    kind = 'canine'         # class variable shared by all instances

    def __init__(self, name):
        self.name = name    # instance variable unique to each instance

>>> d = Dog('Fido')
>>> e = Dog('Buddy')
>>> d.kind                  # shared by all dogs 'canine'
>>> e.kind                  # shared by all dogs 'canine'
>>> d.name                  # unique to d 'Fido'
>>> e.name                  # unique to e 'Buddy' ```

What you are looking for, as @rassar suggested, is:

class Obj:
    def __init__(self):
        self.x = random.randint(1,1000)

a = Obj()
b = Obj()
c = Obj()

print(a.x, b.x, c.x)
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
felipe
  • 7,324
  • 2
  • 28
  • 37