IUnknown
IUnknown

Reputation: 9819

Initializing static member variable in a function

Is it possible to have static variables within class functions(as in C++).
The following does not give me what is desired.
The motivation is to initialize(very expensive process) a lookup list inside a function - but only if and when it is called.
Subsequent invocations of the same function should not need the variable to be initialized again.
Is there an idiom to achieve this?
Its fine if the function is aligned to the class;so that the value of rules is then available to all instances of 'A'

>>> class A:
...     def func(self):
...         if not hasattr(self.func,"rules"):
...             print 'initialize'
...             rules=[8,7,6]
...         rules.append(4)
...         return rules
...         
>>> a=A()
>>> for x in range(5):
...     print a.func()
...     

initialize
[8, 7, 6, 4]
initialize
[8, 7, 6, 4]
initialize
[8, 7, 6, 4]
initialize
[8, 7, 6, 4]
initialize
[8, 7, 6, 4]

Upvotes: 1

Views: 124

Answers (2)

jamylak
jamylak

Reputation: 133634

class A(object): # subclass object for newstyle class
    def func(self, rules=[]):
        if not rules:
            rules[:] = [8, 7, 6]        
        rules.append(4)
        return rules

>>> a = A()
>>> for x in range(5):
        print a.func()


[8, 7, 6, 4]
[8, 7, 6, 4, 4]
[8, 7, 6, 4, 4, 4]
[8, 7, 6, 4, 4, 4, 4]
[8, 7, 6, 4, 4, 4, 4, 4]

Upvotes: 2

BrenBarn
BrenBarn

Reputation: 251458

If you want the variable to be associated with the class, store it on the class:

class A(object):
    def func(self):
        if not hasattr(A,"rules"):
            print 'initialize'
            A.rules=[8,7,6]
        A.rules.append(4)
        return rules

Upvotes: 1

Related Questions