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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果你想计算一个方法被调用的次数,无论哪个实例调用它,你都可以使用这样的类成员:
当你这样定义
calls
时: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:
When you define
calls
this way:Python places the key-value pair ('calls', 0) in
Foo.__dict__
.It can be accessed with
Foo.calls
.Instances of
Foo
, such asfoo=Foo()
, can access it withfoo.calls
as well.To assign new values to
Foo.calls
you must useFoo.calls = ...
.Instances can not use
foo.calls = ...
because that causes Python to place a new and different key-value pair infoo.__dict__
, where instance members are kept.这是一个向函数添加计数的装饰器。
用法:
Here's a decorator adding counting to a function.
Usage:
下面是一些计算同一类的所有对象的调用次数的示例:
这就是证明:
因此您可以通过给出对象名称或类名称来读取它。
Here is some example counting the number of calls of all objects of the same class:
And this is the proof:
so you can read it by giving the object name or class name.
这是一种简单的方法:
或者,如果您不喜欢在每次调用时都执行 if,您可以这样做:
Here's one simplistic way to do it:
Or if you don't like the if being executed on every call, you can do: