listcomps4thewin
listcomps4thewin

Reputation: 83

How to Create Shared Class Attributes between Classes in Python

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?

Upvotes: 3

Views: 2040

Answers (1)

valeriored83
valeriored83

Reputation: 141

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)

Upvotes: 4

Related Questions