Anstatt eine Funktion mit einer statischen lokalen Variablen zu erstellen, können Sie jederzeit ein sogenanntes "Funktionsobjekt" erstellen und ihm eine Standard-Mitgliedsvariable (nicht statisch) zuweisen.
Da Sie ein Beispiel für C ++ angegeben haben, werde ich zunächst erklären, was ein "Funktionsobjekt" in C ++ ist. Ein "Funktionsobjekt" ist einfach eine beliebige Klasse mit einer Überladung operator(). Instanzen der Klasse verhalten sich wie Funktionen. Sie können beispielsweise int x = square(5);auch dann schreiben , wenn squarees sich um ein Objekt (mit Überladung operator()) handelt und technisch gesehen keine "Funktion". Sie können einem Funktionsobjekt alle Funktionen zuweisen, die Sie einem Klassenobjekt geben könnten.
# 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;
In Python können wir auch überladen, operator()außer dass die Methode stattdessen den Namen hat __call__:
Hier ist eine Klassendefinition:
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
Hier ist ein Beispiel für die verwendete Klasse:
from foo import foo
for i in range(0, 5):
foo() # function call
Die auf der Konsole gedruckte Ausgabe lautet:
counter is 1
counter is 2
counter is 3
counter is 4
counter is 5
Wenn Ihre Funktion Eingabeargumente annehmen soll, können Sie diese auch hinzufügen __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
_Präfix zu verwenden.