matlab - 在静态基类方法中访问子类构造函数/方法
问题描述
我有一个抽象基类Parent
和两个子类,Child1
和Child2
。两个孩子都实现了一个由父母抽象定义的静态方法myStaticTransform
。
目标是在 Parent 中创建一个静态方法,myStaticBuilder
它会进行一些计算,调用适当的myStaticTransform
方法,然后使用该数据创建适当的子类的实例。现在我把它定义为一个实例方法,就像这样。
% Parent.m
function child = myNotStaticBuilder(this)
% Do complicated math
x = 1 + 2;
% Transform the data (using this means the child class will dispatch its appropriate method
y = this.myStaticTransform(x);
% Get the child constructor the only way I know (it's gross and I hate it but shrug emoji)
childConstructor = str2func(class(this));
% Return the appropriate child object
child = childConstructor(y);
end
这不是安抚,但它有效,所以我可以忍受它。据我所知,这就是互联网认为应该这样做的方式。美好的。
但理想情况下,我想让这个函数静态,因为它不依赖于调用之前存在的任何对象。如果这是静态的,显然我将无法引用this
(很明显我是一名 Python 程序员)。如果没有该引用,我不知道如何访问子构造函数。据我所知,我还必须调用Parent.myStaticTransform
,我认为(但尚未验证)会引发错误,因为父实现是抽象的。
有没有办法按照我的意愿把它变成一个静态方法,还是我应该感谢 Matlab 有类而不指望它们做对?
在 Python 中,我会使用类方法而不是静态方法,据我所知,这是 Matlab 没有的概念。
@classmethod
def myClassBuilder(cls):
# Do complicated math
x = 1 + 2;
# Transform the data
y = cls.myStaticTransform(x)
# Return the appropriate child object
child = cls(y)
return child