static class python code example

Example 1: static class python

#To create a static method, just add "@staticmethod" before defining it.

>>>class Calculator:
    # create static method
    @staticmethod
    def multiplyNums(x, y):
        return x * y

>>>print('Product:', Calculator.multiplyNums(15, 110))
Product:1650

Example 2: python class static variable

>>> class MyClass:
...     i = 3
...
>>> MyClass.i
3

Example 3: instance method in python

# Instance Method Example in Python 
class Student:
    
    def __init__(self, a, b):
        self.a = a
        self.b = b 
    
    def avg(self):
        return (self.a + self.b) / 2

s1 = Student(10, 20)
print( s1.avg() )

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'

Tags:

Misc Example