Zamiast tworzyć funkcję posiadającą statyczną zmienną lokalną, zawsze możesz utworzyć tak zwany „obiekt funkcji” i nadać jej standardową (niestatyczną) zmienną składową.
Ponieważ podałeś przykład napisany w C ++, najpierw wyjaśnię, czym jest „obiekt funkcji” w C ++. „Obiekt funkcji” to po prostu dowolna klasa z przeciążeniem operator(). Instancje klasy będą zachowywać się jak funkcje. Na przykład możesz pisać, int x = square(5);nawet jeśli squarejest obiektem (z przeciążeniem operator()) i technicznie nie jest „funkcją”. Możesz nadać obiektowi funkcyjnemu dowolną funkcję, którą możesz nadać obiektowi klasy.
# C++ function object
class Foo_class {
private:
int counter;
public:
Foo_class() {
counter = 0;
}
void operator() () {
counter++;
printf("counter is %d\n", counter);
}
};
Foo_class foo;
W Pythonie możemy również przeciążać, operator()ale zamiast tego nazwa metody __call__:
Oto definicja klasy:
class Foo_class:
def __init__(self): # __init__ is similair to a C++ class constructor
self.counter = 0
# self.counter is like a static member
# variable of a function named "foo"
def __call__(self): # overload operator()
self.counter += 1
print("counter is %d" % self.counter);
foo = Foo_class() # call the constructor
Oto przykład zastosowanej klasy:
from foo import foo
for i in range(0, 5):
foo() # function call
Dane wyjściowe drukowane na konsoli to:
counter is 1
counter is 2
counter is 3
counter is 4
counter is 5
Jeśli chcesz, aby twoja funkcja pobierała argumenty wejściowe, możesz również dodać je do __call__:
# FILE: foo.py - - - - - - - - - - - - - - - - - - - - - - - - -
class Foo_class:
def __init__(self):
self.counter = 0
def __call__(self, x, y, z): # overload operator()
self.counter += 1
print("counter is %d" % self.counter);
print("x, y, z, are %d, %d, %d" % (x, y, z));
foo = Foo_class() # call the constructor
# FILE: main.py - - - - - - - - - - - - - - - - - - - - - - - - - - - -
from foo import foo
for i in range(0, 5):
foo(7, 8, 9) # function call
# Console Output - - - - - - - - - - - - - - - - - - - - - - - - - -
counter is 1
x, y, z, are 7, 8, 9
counter is 2
x, y, z, are 7, 8, 9
counter is 3
x, y, z, are 7, 8, 9
counter is 4
x, y, z, are 7, 8, 9
counter is 5
x, y, z, are 7, 8, 9
_prefiksu.