Manidip Sengupta
Manidip Sengupta

Reputation: 3611

How do you define class variables accessible by all instances

I want to define a array with class-wide scope/access by all instances. Example module (bc.py):

class B:
    glist = []  # array common to all instances

    def __init__(self, number):
        glist.append(number)                                                                                                            

    def printCurrentList():
        print ('Current List:', glist)

class C:
    def __init__(self):
        b1 = B(7)
        b2 = B(2)
        b3 = B(8)

    def printNow(self):
        B.printCurrentList()

I am calling this from file a.py, as:

from bc import C                                                                                                                        
C().printNow()

Getting error as:

python a.py
Traceback (most recent call last):
  File "a.py", line 2, in <module>
    C().printNow()
  File "/Users/manidipsengupta/pytorials/bc.py", line 16, in __init__
    b1 = B(7)
  File "/Users/manidipsengupta/pytorials/bc.py", line 7, in __init__
    glist.append(number)
NameError: name 'glist' is not defined

What should be the correct syntax for this? Thank you.

Upvotes: 0

Views: 61

Answers (2)

Daniel
Daniel

Reputation: 42748

You have access class variables through class or instance:

class B:
    glist = []  # array common to all instances

    def __init__(self, number):
        self.glist.append(number)                                                                                                            

    @classmethod
    def printCurrentList(cls):
        print ('Current List:', cls.glist)

Upvotes: 1

Cory Kramer
Cory Kramer

Reputation: 117856

Either

B.glist.append(number)

or

self.glist.append(number)

will work. I'd prefer the former as it better shows that glist is a static class variable, instead of per instance.

Upvotes: 4

Related Questions