3

I asked about this yesterday, but I botched writing up my question so much that by the time I realized what I typed, all the replies were solutions to a different miss-worded problem I didn't have. Sorry for the foolish type up last time.

I have two Classes, and I want them to able to share a common list without having to pass it as a parameter. I also want to create a method that will scramble that list, and I want the list to be the same newly scrambled list in both Class A and Class B.

I figured this was a case for inheritance, so I made a Parent Class and set the list as a class attribute and made a method to scramble, but the list variable is oddly enough being now treated as an instance variable of the children.

class A:
    lst = []
    target = 0

    def generateNewLst(self, randomRange, listSize):
        self.lst = [random.randint(*randomRange) for i in range(listSize)]

class B(A):
    pass

class C(A):
    pass

My inherited method works just fine:

a = B()
a.generateNewLst((0, 10), 3)
a.lst  # => [2,5,7]

but when I create another B:

b = B()
b.lst  # => [] not shared when I want it to be

This CANNOT be solved with a class attribute in B, because that won't solve the more important below issue...

c = C()
c.lst  # => [] not shared when I want it to be

TL;DR: I want a Class attribute that shares between every instance of both classes. I want a.lst == b.lst == c.lst every time I run generateNewList on ONE of any of those instances.

How should I reorganize my setup to work the way I want it to?

2
  • Possible duplicate of python class attribute Commented Sep 29, 2019 at 14:36
  • You need to refer to the class member as A.lst in all cases. Commented Sep 29, 2019 at 14:40

1 Answer 1

4

You need a static variable. To do so make the method generateNewLst static and let him update the static variable lst and not a member variable lst that would belong to the instance of the class and not to the class itself.

class A:
    lst = []

    @staticmethod
    def generateNewLst(randomRange, listSize):
        A.lst = [random.randint(*randomRange) for i in range(listSize)]

class B(A):
    pass

class C(A):
    pass

Then once you generate the lst you will have it for all classes.

a = B()
B.generateNewLst((0, 10), 3)
# the same list is available for all classes
print(A.lst) 
print(B.lst)
print(C.lst)
Sign up to request clarification or add additional context in comments.

2 Comments

@OverLordGoldDragon what do you mean? I just tested with the __init__ in one or all the classes and it runs. Why should it fail?
@valeriored83 I figured an additional scope of inheritance from the question (not the case) - nevermind, all is good

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.