cas*_*sen 5 oop matlab static class
授予以下代码:
classdef highLowGame
methods(Static)
function [wonAmount, noGuesses] = run(gambledAmount)
noGuesses = 'something';
wonAmount = highLowGame.getPayout(gambledAmount, noGuesses); % <---
end
function wonAmount = getPayout(gambledAmount, noGuesses)
wonAmount = 'something';
end
end
end
Run Code Online (Sandbox Code Playgroud)
有没有办法在不必编写类名的情况下调用同一个类(静态内部)方法的静态方法?像"self.getPayout(...)"之类的东西 - 如果该类最终得到500行并且我想重命名它.
不回答你的问题直接,但值得一提的是,你还可以把"本地功能"你结束后classdef在块class.m文件,这些行为类似于私有静态方法,但是你并不需要使用类调用它们名称.即
% myclass.m
classdef myclass
methods ( Static )
function x = foo()
x = iMyFoo();
end
end
end
function x = iMyFoo()
x = rand();
end
% end of myclass.m
Run Code Online (Sandbox Code Playgroud)
据我所知,“不”带有“但是”。一般来说,只能用类名来指定静态方法。但是,您可以绕过限制,因为 MATLAB 有 feval:
classdef testStatic
methods (Static)
function p = getPi() %this is a static method
p = 3.14;
end
end
methods
function self = testStatic()
testStatic.getPi %these are all equivalent
feval(sprintf('%s.getPi',class(self)))
feval(sprintf('%s.getPi',mfilename('class')))
end
end
end
Run Code Online (Sandbox Code Playgroud)
在这里,class(self) 和 mfilename 都计算为“testStatic”,因此上面的函数最终计算为“testStatic.getPi”。
或者,您也可以编写一个非静态方法 self.callStatic; 然后总是使用它。在其中,只需调用 testStatic.getPi 即可。然后你只需要改变这一行。
| 归档时间: |
|
| 查看次数: |
2731 次 |
| 最近记录: |