22

I am relatively new to python I would like to run a block of code only once for a class. Like the static block in java.

for eg:

class ABC:
    execute this once for a class.

Is there any such options available in python?

In java we write it like this. This is executed only once for a class, at the time the class is loaded. Not for every object creation

public class StaticExample{
    static {
        System.out.println("This is first static block");
    }
}

Thanks

M S
  • 3,995
  • 3
  • 25
  • 36

2 Answers2

25

To do this just put the code directly under the class definition (parallel to the function definitions for the class.

All code directly in the class gets executed upon creation of that type in the class' namespace. Example:

class Test:
    i = 3
    y = 3 * i
    def testF(self):
        print Test.y

v = Test()
v.testF()
# >> 9

Just to fill out the last bit of information for you: your method function defs are also being executed (just like they get "executed" when you define a function on the global namespace), but they aren't called. It just happens to be that executing a def has no obviously visible results.

Python's object-oriented-ness is quite clever, but it takes a bit to get your head around it! Keep it up, it's a very fun language.

Chris Pfohl
  • 18,220
  • 9
  • 68
  • 111
13
>>> class MyClass():
...     print "static block was executed"
... 
static block was executed
>>> obj = MyClass()
>>>

See here for more information about static variables/functions in Python: Static class variables in Python

Community
  • 1
  • 1
naeg
  • 3,944
  • 3
  • 24
  • 29