Python 中函数的静态成员?

发布于 2024-12-14 23:22:54 字数 387 浏览 1 评论 0原文

可能的重复:
Python 中的静态类变量
Python 中静态变量的等效项是什么功能?

如何在 Python 中使用静态字段?

例如,我想计算该函数被调用的次数 - 我该怎么做?

Possible Duplicate:
Static class variables in Python
What is the Python equivalent of static variables inside a function?

How can I use static fields in Python ?

for example i want to count how many times the function has been called - how can i do this ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

拍不死你 2024-12-21 23:22:54

如果你想计算一个方法被调用的次数,无论哪个实例调用它,你都可以使用这样的类成员:

class Foo(object):
    calls=0            # <--- call is a class member
    def baz(self):
        Foo.calls+=1

foo=Foo()
bar=Foo()
for i in range(100): 
    foo.baz()
    bar.baz()
print('Foo.baz was called {n} times'.format(n=foo.calls))
# Foo.baz was called 200 times

当你这样定义calls时:

class Foo(object):
    calls=0            

Python放置键值对Foo.__dict__ 中的 ('calls', 0) 对。

可以通过 Foo.calls访问它。
Foo 的实例(例如 foo=Foo())也可以通过 foo.calls 访问它。

要为Foo.calls分配新值,您必须使用Foo.calls = ...
实例不能使用 foo.calls = ... ,因为这会导致 Python 在保存实例成员的 foo.__dict__ 中放置一个新的不同键值对。

If you wish to count how many times a method has been called, no matter which instance called it, you could use a class member like this:

class Foo(object):
    calls=0            # <--- call is a class member
    def baz(self):
        Foo.calls+=1

foo=Foo()
bar=Foo()
for i in range(100): 
    foo.baz()
    bar.baz()
print('Foo.baz was called {n} times'.format(n=foo.calls))
# Foo.baz was called 200 times

When you define calls this way:

class Foo(object):
    calls=0            

Python places the key-value pair ('calls', 0) in Foo.__dict__.

It can be accessed with Foo.calls.
Instances of Foo, such as foo=Foo(), can access it with foo.calls as well.

To assign new values to Foo.calls you must use Foo.calls = ....
Instances can not use foo.calls = ... because that causes Python to place a new and different key-value pair in foo.__dict__, where instance members are kept.

许久 2024-12-21 23:22:54

这是一个向函数添加计数的装饰器。

import functools

def count_calls(func):
    @functools.wraps(func)
    def decor(*args, **kwargs):
        decor.count += 1
        return func(*args, **kwargs)
    decor.count = 0
    return decor

用法:

>>> @count_calls
... def foo():
...     pass
...
>>> foo.count
0
>>> foo()
>>> foo.count
1

Here's a decorator adding counting to a function.

import functools

def count_calls(func):
    @functools.wraps(func)
    def decor(*args, **kwargs):
        decor.count += 1
        return func(*args, **kwargs)
    decor.count = 0
    return decor

Usage:

>>> @count_calls
... def foo():
...     pass
...
>>> foo.count
0
>>> foo()
>>> foo.count
1
时光无声 2024-12-21 23:22:54

下面是一些计算同一类的所有对象的调用次数的示例:

class Swallow():
    i = 0 # will be used for counting calls of fly()
    def fly(self):
        Swallow.i += 1

这就是证明:

>>> a = Swallow()
>>> b = Swallow()
>>> a.fly()
>>> a.i
1
>>> Swallow.i
1
>>> b.fly()
>>> b.i
2
>>> Swallow.i
2

因此您可以通过给出对​​象名称或类名称来读取它。

Here is some example counting the number of calls of all objects of the same class:

class Swallow():
    i = 0 # will be used for counting calls of fly()
    def fly(self):
        Swallow.i += 1

And this is the proof:

>>> a = Swallow()
>>> b = Swallow()
>>> a.fly()
>>> a.i
1
>>> Swallow.i
1
>>> b.fly()
>>> b.i
2
>>> Swallow.i
2

so you can read it by giving the object name or class name.

能怎样 2024-12-21 23:22:54

这是一种简单的方法:

def func():
    if not hasattr(func, 'counter'):
        func.counter = 0
    func.counter += 1
    counter = 0 # Not the same as `func.counter`
    print(func.counter)

或者,如果您不喜欢在每次调用时都执行 if,您可以这样做:

def func():
    func.counter += 1
    print(func.counter)
func.counter = 0

Here's one simplistic way to do it:

def func():
    if not hasattr(func, 'counter'):
        func.counter = 0
    func.counter += 1
    counter = 0 # Not the same as `func.counter`
    print(func.counter)

Or if you don't like the if being executed on every call, you can do:

def func():
    func.counter += 1
    print(func.counter)
func.counter = 0
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文