python static code example

Example 1: static methods in python

class Calculator:

    # create addNumbers static method
    @staticmethod
    def addNumbers(x, y):
        return x + y

print('Product:', Calculator.addNumbers(15, 110))

Example 2: staticmethod python

import random

class Example:
  	# A static method doesn't take the self argument and
    # cannot access class members.
	@staticmethod
    def choose(l: list) -> int:
    	return random.choice(l)
    
    def __init__(self, l: list):
      self.number = self.choose(l)

Example 3: static methods in python

class Calculator:

    def addNumbers(x, y):
        return x + y

# create addNumbers static method
Calculator.addNumbers = staticmethod(Calculator.addNumbers)

print('Product:', Calculator.addNumbers(15, 110))

Example 4: cls in python

import os
clear = lambda: os.system('cls')

Example 5: creating a static property in python

class Example:
  staticVariable = 5
  
print(Example.staticVariable)  # Prints '5'

instance = Example()
print(instance.staticVariable)  # Prints '5'

instance.staticVaraible = 6
print(instance.staticVariabel)  # Prints '6'
print(Example.staticVariable)  # Prints '5'

Example.staticVariable = 7
print(Example.staticVariable)  # Prints '7'