问题描述
我希望类的构造函数自动确定调用函数的完整路径,以便该类可以编写一个保证位于调用者目录中的文件(而不是偶然出现的pwd()
).
I'd like the constructor of a class to automatically determine the full path to the calling function, so that that class can write a file that's guaranteed to be in the caller's directory (instead of whatever happens to be the pwd()
).
所以,我有以下设置:
在some_path/test.m
中:
function test
SomeClass()
end
在some_path/some_subdir/SomeClass.m
中:
classdef SomeClass < handle
methods
function obj = SomeClass()
evalin('caller', 'mfilename(''fullpath'')')
end
end
end
致电test()
时,我得到以下信息:
When I call test()
, I get the following:
>> test()
ans =
'some_path/some_subdir/SomeClass.m' % <- ...why?
我希望对evalin('caller', ...)
中的mfilename()
进行调用以在test()
内部求值,但是显然,这不会发生...
I expected the call to mfilename()
in evalin('caller', ...)
to evaluate inside test()
, but apparently, that doesn't happen...
嵌套evalins
似乎没有帮助:
...
function obj = SomeClass()
evalin('caller', ' evalin(''caller'', ''mfilename(''''fullpath'''')'') ')
end
...
>> test()
ans =
'some_path/some_subdir/SomeClass.m'
使此功能生效的唯一方法是远不那么直观的dbstack()
:
The only way to get this to work is the far less intuitive dbstack()
:
...
function obj = SomeClass()
S = dbstack(1, '-completenames');
S(1).file
end
...
>> test()
ans =
'some_path/test.m'
我想念什么?
推荐答案
看来您不能为此目的使用evelin
.来自文档:
It looks like you cannot use evelin
for this purpose. From the documentation:
据我了解,在评估表达式之前未恢复调用函数的完整上下文,只有调用函数工作区中的变量才可用.
From that I read that not the full context of the calling function is recovered before evaluating the expression, only variables in the workspace of the calling function are made available.
同一文档页面也提到了此限制:
That same documentation page also mentions this limitation:
这与仅调用者的工作空间可用而不是整个上下文可用的观念是一致的.该表达式实际上并没有像在调用函数中那样编写.
That is consistent with the notion that only the caller's workspace is made available, not the full context. The expression is not actually evaluated as if it were written inside the calling function.
我已经用一个简单的M文件功能重复了您的实验,只是为了证明这确实不是特定于类或构造函数的,而是通常适用于任何地方的任何函数.
I have repeated your experiment with a simple M-file function, just to verify this indeed is not specific to classes or constructors, but generally applies to any function, anywhere.
dbstack
选项是解决方法.
这篇关于获取调用构造函数的函数的完整路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!