Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there static block in class in python

Tags:

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

like image 738
M S Avatar asked Oct 24 '11 18:10

M S


Video Answer


2 Answers

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.

like image 79
Chris Pfohl Avatar answered Nov 15 '22 17:11

Chris Pfohl


>>> 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

like image 39
naeg Avatar answered Nov 15 '22 17:11

naeg