Alih-alih membuat fungsi yang memiliki variabel lokal statis, Anda selalu dapat membuat apa yang disebut "objek fungsi" dan memberinya variabel anggota standar (non-statis).
Karena Anda memberi contoh C ++ yang ditulis, saya pertama-tama akan menjelaskan apa "objek fungsi" di C ++. "Objek fungsi" adalah kelas apa saja dengan kelebihan beban operator(). Contoh kelas akan berperilaku seperti fungsi. Sebagai contoh, Anda dapat menulis int x = square(5);meskipun squareobjek (dengan kelebihan beban operator()) dan secara teknis bukan "fungsi." Anda bisa memberikan objek-fungsi salah satu fitur yang bisa Anda berikan pada objek kelas.
# 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;
Dalam Python, kita juga bisa membebani operator()kecuali bahwa metode ini dinamai __call__:
Berikut adalah definisi kelas:
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
Berikut adalah contoh kelas yang digunakan:
from foo import foo
for i in range(0, 5):
foo() # function call
Output yang dicetak ke konsol adalah:
counter is 1
counter is 2
counter is 3
counter is 4
counter is 5
Jika Anda ingin fungsi Anda mengambil argumen input, Anda dapat menambahkannya __call__juga:
# 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
_awalan konvensional .