static method in python code example
Example 1: python static variable in function
"""1/You can add attributes to a function, and use it as a
static variable."""
def foo():
foo.counter += 1
print ("Counter is %d" % foo.counter)
foo.counter = 0
"""2/If you want the counter initialization code at the top
instead of the bottom, you can create a decorator:"""
def static_vars(**kwargs):
def decorate(func):
for k in kwargs:
setattr(func, k, kwargs[k])
return func
return decorate
@static_vars(counter=0)
def foo():
foo.counter += 1
print ("Counter is %d" % foo.counter)
"""3/Alternatively, if you don't want to setup the variable
outside the function, you can use hasattr() to avoid an
AttributeError exception:"""
def myfunc():
if not hasattr(myfunc, "counter"):
myfunc.counter = 0
myfunc.counter += 1
Example 2: static class python
>>>class Calculator:
@staticmethod
def multiplyNums(x, y):
return x * y
>>>print('Product:', Calculator.multiplyNums(15, 110))
Product:1650
Example 3: static methods in python
class Calculator:
@staticmethod
def addNumbers(x, y):
return x + y
print('Product:', Calculator.addNumbers(15, 110))
Example 4: staticmethod python
import random
class Example:
@staticmethod
def choose(l: list) -> int:
return random.choice(l)
def __init__(self, l: list):
self.number = self.choose(l)
Example 5: static methods in python
class Calculator:
def addNumbers(x, y):
return x + y
Calculator.addNumbers = staticmethod(Calculator.addNumbers)
print('Product:', Calculator.addNumbers(15, 110))