Single-File Object-Oriented Script?

조회 수: 23 (최근 30일)
Silas Henderson
Silas Henderson 2019년 6월 14일
댓글: Silas Henderson 2019년 6월 14일
How can I define a class and instantiate it within the same script? Something like ...
object = some_class()
while 1
object.method
end
classdef(some_class)
properties: ...
methods: ...
end
I understand that class definitions, in Matlab, are supposed to be implemented in separate files. I'm asking about some kind of work-around...
with the sole purpose of keeping the script self-contained, even if the actual program stretches out. A guess is shown below.
string = "classdef(.....)"
classdef_file = export-to-file(string)
load(classdef_file)
object = some_class()
while 1
object.method
end
... or maybe something with C code, or handle objects? Like... some way to make a 'pseudo-class' that acts like a class but has different implementation?
I'm putting this out there because someone must have found a similar solution for defining functions in the script prior to 2016.
Here are the half-solutions that I'm aware of:
  • Jupyter Notebooks with %%file method.
  • Define a structure and just use anonymous functions, a.b = @ (x) ...
If anyone finds or knows a solution, this would be awesome!

채택된 답변

Matt J
Matt J 2019년 6월 14일
편집: Matt J 2019년 6월 14일
You could just create a static class method that runs what you would normally run in the workspace of the script,
classdef some_class
methods(Static)
function script_code
object = some_class();
while 1
object.some_method();
end
end
end
%% Non-Static class definitions
properties
...
end
methods
function some_method(obj)
end
....
end
end

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Class Introspection and Metadata에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by