Saltar al contenido

Variable estática en el ejemplo de código de clase de Python

Ejemplo 1: variable estática de Python en función

#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
  
#____________________________________________________________#

Ejemplo 2: Python de clase estática

#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

Ejemplo 3: variable estática de la clase Python

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

Ejemplo 4: crear una propiedad estática en 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'
¡Haz clic para puntuar esta entrada!
(Votos: 0 Promedio: 0)



Utiliza Nuestro Buscador

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *