Can I Dynamically Overload A Class Method?
显示 更早的评论
Hi All,
Context: I'm attempting to overload a method of class without touching the class definition or explicitly declaring a subclass.
Question: Is it possible to dynamically overload a class method either by directly overloading, dynamically creating a subclass, or intercepting method calls?
Prior Work:
The odd error message produced by the following example gives me a dim hope that its possible directly . . .
Here's an example class
classdef Hello
methods
function sayHi(obj)
fprintf('Hi\n')
end
end
end
I then attempt to dynamically override the sayHi function, producing an error as follows:
helloObj = Hello;
sayHola = @(obj) fprintf('Hola\n')
helloObj.sayHi = sayHola;
Assignment not supported because the result of method 'sayHi' is a temporary value.
Is there a way to make "sayHi" produce a non temporary value? Or is that saying that @helloObj.sayHi is itself a temporary value?
采纳的回答
更多回答(1 个)
You can't dynamically overload a class method, but you can get the same effect by making function handle properties that dictate the method's behavior. For example,
classdef Hello
properties
greeting=@() fprintf('Hi\n');
end
methods
function sayHi(obj)
obj.greeting();
end
end
end
and now you can make dynamic changes, like
>> helloObj = Hello; helloObj.sayHi
Hi
>> helloObj.greeting = @()fprintf('Hola\n'); helloObj.sayHi
Hola
4 个评论
Of course, you should be mindful that these kinds of things can often be accomplished with simpler kinds of properties/class designs. In your example, it seems sufficient to use a simple string property to guide the output of sayHi(), like in,
classdef Hello
properties
greeting="Hi";
end
methods
function sayHi(obj)
disp(obj.greeting);
end
end
end
>> helloObj.greeting="Bonjour"; helloObj.sayHi
Bonjour
Too bad, but maybe if you elaborate on the constraints of the situation, better recommendations can be made. Why exactly can't the class be modified or subclassed? What about a container class:
classdef HelloContainer
properties
HelloObj
end
methods
function obj = HelloContainer(HelloObj)
obj.HelloObj=HelloObj;
end
function sayHi(obj)
fprintf('Hola\n')
end
end
end
类别
在 帮助中心 和 File Exchange 中查找有关 Properties 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!