首页 > 解决方案 > 如何计算构造函数被调用的次数?

问题描述

我在下面有这个 Python 代码。下面是我尝试将其转换为 MATLAB 代码。我是新手classdef,我正在做转换练习。counter(想要计算我调用构造函数的次数)的问题,我希望得到有关如何纠正我的转换的反馈。

Python版本:

 class Test:
    counter = 0
    def __init__(self, id):
        self.id = id
        Test.counter += 1

我对 MATLAB 转换的尝试:

classdef Test
    properties
        counter=0;
        id;
    end
    methods
        function self= Test(id)
            self.id = id;
            self.counter = self.counter+1;
        end
    end
end

标签: matlabclassoopconstructor

解决方案


我找到了这个解决方案

classdef Test
    properties
        id;
    end
    methods
        function self= Test(id)
            self.id = id;
        end
    end
    methods (Static)
        function c= counter
            persistent Count;
            if isempty(Count)
                Count = 1;
            else
                Count = Count + 1;
            end
            c = Count;
        end
    end
end

推荐阅读