1

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]
2
  • 2
    Do you want that variable "rules" to be associated with the class or with the instance? Commented May 28, 2013 at 5:29
  • with the class - I have edited the question to reflect that Commented May 28, 2013 at 5:34

2 Answers 2

2
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]
Sign up to request clarification or add additional context in comments.

6 Comments

but that would calculate rules on parsing A, not on first use.
@ThomasFenzl sorry missed that part
@ThomasFenzl I've fixed that now
This is perfect - but please explain the principle behind this.What makes this behave differently from hasattr?
@IUnknown rules is a member of the function itself. It begins empty, on the first run of func() it gets filled with [8, 7, 6]
|
1

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

Comments

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.