What is the variable 'self' in MATLAB class?
115 次查看(过去 30 天)
显示 更早的评论
Hi ! While I look through the code that includes class, I found that variable 'self' behaves like 'preserved' variable.
For example...
classdef Vocabulary < handle
properties
words = {};
end
methods
function add_word(self, word, audio_signals)
new_word = Word(word);
% Concatenate and train
new_word.train(extract_features(cell2mat(audio_signals)'));
self.words.(char(word)) = new_word;
end
add_word function has 3 arguments including 'self' argument. But this function is called with only 2 arguments, like 'add_word(word_labels(~~~), train_audio_signals(~~~))'.
Not only the 'add_word' fucntion, but also the other functions use similar way.
Can anyone tell me the usage of variable 'self'?
I really appreciate your help !
0 个评论
回答(2 个)
Daniel Shub
2012-9-24
There is nothing special about the variable "self". In MATLAB many people use "obj" instead. There is something special about the first argument to a function. The class of the first argument determines the class of the method to be used. In other words
function add_word(self, word, audio_signals)
and
function add_word(obj, word, audio_signals)
are the same, but
function add_word(word, audio_signals, self)
is very different.
I doubt you are calling
add_word(word_labels(~~~), train_audio_signals(~~~))
and bet you are calling
myVocabularyObject.add_word(word_labels(~~~), train_audio_signals(~~~))
where myVocabularyObject is an object of the Vocabulary class. This is essentially the same as calling
add_word(myVocabularyObject, word_labels(~~~), train_audio_signals(~~~))
It is not strictly identical if the subsref method has been overloaded ...
0 个评论
Neeraj Rajpurohit
2020-6-30
As Daniel has rightly written, obj is usually writtern instead of 'self' in definition of methods in MATLAB classes.
If the function you are calling is non-static, and it accesses the the object properties, then self is a must-have arguments.
As you can see in the below class, the function fullName will take no arguments while calling, but we are defining obj as a reference to the class object.
class Name
properties
Name(1, :) char
Surname(1, :) char
end
methods
function name = fullName(obj)
name = obj.Name + obj.Surname
end
end
end
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Methods 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!