1

I started object-oriented programming in python and in my program, I decided to store class instances in array, but I don't know how to access class variables now.

class apixel(object):
    def __init__(self):
        self.posx = random.randint(0, 300)
        self.posy = random.randint(0, 200)
    def do_i_exist():
        print("Yes i do!")

p = [apixel] * 10

for obj in p:
    obj.do_i_exist() #that works
    print(obj.posx)  #but that does not work
1
  • 1
    Your code only "works" because you incorrectly omitted the self argument to the do_i_exist method. Dec 31, 2017 at 22:52

1 Answer 1

5

The issue is that you need to actually instantiate the objects, otherwise __init__ is never called.

Try:

p = [apixel() for _ in range(10)]

Per Craig's comment below, the list comprehension calls the constructor 10 times so you get 10 independent objects.

But, the reason your apixel didn't have a self.posx is that the constructor was never called by your code. You weren't creating a list of instances of your class, but rather a list of references to the class definition.

Per DanielPryden's comment on your OP, you should either change the signature of your do_i_exist method to accept self, or annotate it as static:

# as an instance method, which requires "self":
do_i_exist(self):
    ...

# as a static class method that is the same for all instances:
@staticmethod
do_i_exist():
   ... method body contains NO references to "self"
1
  • 1
    This will create 10 copies of one object. The OP probably wants a list comprehension like p = [apixel() for _ in range(10)] to get 10 independent objects.
    – Craig
    Dec 31, 2017 at 22:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.