【问题标题】:How to access property from static method如何从静态方法访问属性
【发布时间】:2021-04-06 18:41:25
【问题描述】:

正如标题所说,我正在使用构造函数设置一个属性,并希望稍后以静态 get 函数的形式访问该属性。我将如何在 MATLAB 中执行此操作?

classdef Wrapper
    
    properties(Access=public)
        dataStruct
    end
    
    methods
    
        function data = Wrapper(filePath)
            if nargin == 1
                data.dataStruct=load(filePath)
            end
            
        end
    end
        
    methods(Static)
        function platPosition = getPlatPosition()
            platPosition = dataStruct.someField
        end
    end
end

--------------------------
import pkg.Wrapper.*
test = Wrapper('sim.mat')
pos = test.getPlatPosition

【问题讨论】:

    标签: matlab matlab-class


    【解决方案1】:

    据我所知,MATLAB 没有像其他 OOP 语言 [ref] 这样的静态属性。在静态方法中只能使用静态属性。在 MATLAB 类中最接近静态属性的是 Constant 属性。缺点是常量属性必须初始化并且是只读的。在静态方法中,您可以使用类名访问只读/常量属性。

    classdef Wrapper
        
        properties(Constant=true)
            dataStruct=load('\path\to\sim.mat');
        end
        
        methods
            function data = Wrapper()   
                %do something with object
            end
        end
            
        methods(Static=true)
            function platPosition = getPlatPosition()
                platPosition = Wrapper.dataStruct.Fieldname;
            end
        end
    end
    

    在您的情况下,您可以接受 object 作为静态方法的输入参数。

    classdef Wrapper
        
        properties(Access=public)
            dataStruct
        end
        
        methods
        
            function data = Wrapper(filePath)
                if nargin == 1
                    data.dataStruct=load(filePath)
                end
                
            end
        end
            
        methods(Static)
            function platPosition = getPlatPosition(obj)
                platPosition = obj.dataStruct.someField
            end
        end
    end
    --------------------------
    import pkg.Wrapper.*
    test = Wrapper('sim.mat')
    pos = test.getPlatPosition(test);
    

    【讨论】:

      猜你喜欢
      • 2013-02-13
      • 1970-01-01
      • 1970-01-01
      • 2015-12-22
      • 1970-01-01
      • 2012-03-30
      • 1970-01-01
      • 2013-04-27
      • 2022-01-03
      相关资源
      最近更新 更多