Answers for "python static method"

8

python static variable in function

#You can make static variables inside a function in many ways.
#____________________________________________________________#
"""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
  
#Then use the code like this:
@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  # it doesn't exist yet, so initialize it
    myfunc.counter += 1
  
#____________________________________________________________#
Posted by: Guest on March-07-2020
1

staticmethod python

class math:

    @staticmethod
    def add(x, y):
        return x + y

    @staticmethod
    def add5(num):
        return num + 5

    @staticmethod
    def add10(num):
        return num + 10

    @staticmethod
    def pi():
        return 3.14


x = math.add(10, 20)
y = math.add5(x)
z = math.add10(y)
print(x, y, z)
Posted by: Guest on October-20-2021
4

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)
Posted by: Guest on February-01-2021
0

cls in python

import os
clear = lambda: os.system('cls')
Posted by: Guest on September-04-2020
1

class methods in python

@classmethod
def func(cls, args...)
Posted by: Guest on November-14-2020
0

python staticmethod

# python static method in simple explanation
class cls:
    @staticmethod
    def func():
        pass

instance1 = cls()
instance2 = cls()
instance3 = cls()

print(id(cls.func), cls.func)
print(id(instance1.func), instance1.func)
print(id(instance2.func), instance2.func)
print(id(instance3.func), instance3.func)
# they are same thing
Posted by: Guest on August-14-2021

Code answers related to "Java"

Java Answers by Framework

Browse Popular Code Answers by Language