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
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 def
s 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.
>>> 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With