【问题标题】:How to count the number of times a constructor is called?如何计算构造函数被调用的次数?
【发布时间】:2021-01-09 04:22:48
【问题描述】:

我在下面有这个 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

【问题讨论】:

  • 构造函数总是为每个对象调用一次。 Python 代码中的 counter 是否真的有一个不是 1 的值?

标签: matlab class oop constructor


【解决方案1】:

我找到了这个解决方案

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

【讨论】:

  • 通常应该避免使用持久变量,我不确定这里的用例是什么——你如何想象调用这个静态方法?如果从外部代码调用它(因为它是公共方法)并且计数器发生变化怎么办?在您的解决方案中,甚至没有调用 counter 函数,所以我不确定它有什么帮助..
  • 这是一个有趣的解决方案,但构造函数确实仍然没有计数,我猜您可能需要在不增加计数的情况下检索计数?
  • @wolfie:你为什么说通常应该避免使用持久变量?它们确实非常有用,完全不像全局变量。
  • @Wolfie:a=Test(5) .....b=Test(8)。在这种情况下 a.counter==1 和 b.counter==2。
  • a.counter 返回 1,然后是 2,然后是 3,然后是 4,...每次调用它时,它都会向内部计数器加一。该函数不被构造函数调用,因此调用构造函数不会增加计数器。您需要为类添加一个值,并将该值设置为构造函数中的当前计数器。
猜你喜欢
  • 1970-01-01
  • 2011-02-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-11
  • 2012-06-11
相关资源
最近更新 更多