首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在Python中保存类调用中插入的函数数量?

如何在Python中保存类调用中插入的函数数量?
EN

Stack Overflow用户
提问于 2021-02-09 15:37:37
回答 1查看 19关注 0票数 1

如何节省函数的needed_function调用次数?它被many_functions_that_calling_needed_function1等函数调用。我有如下的类模式:

代码语言:javascript
复制
class MyClass
    def __init__
...
    def my_function
    ...
    @staticmethod
    def needed_function
        if first_statement:
            """Count number of calling if statement"""
        elif second statement:
            """Count number of calling elif statement"""

    def many_functions_that_calling_needed_function1
        self.needed_function()

    def many_functions_that_calling_needed_function2
        self.needed_function()

    def many_functions_that_calling_needed_function3
        self.needed_function()

    def many_functions_that_calling_needed_function4
        self.needed_function()
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-02-09 16:16:30

如果你只需要跟踪一个类(一个方法)内的一个函数被调用了多少次,你可以这样做:

代码语言:javascript
复制
class TestClass:
    def __init__(self):
        self.calls=0

    def needed_function(self):
        """if this function gets called, increase the value of self.calls by 1"""
        self.calls+=1
        # add whatever else you want here

c=TestClass()
print(c.calls)    # prints 0 cause needed_function hasn't been called yet
c.needed_function()    # needed_function is called here
print(c.calls)     # prints 1
c.needed_function()    # called again
print(c.calls)    # prints 2
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66114753

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档