What is the variable 'self' in MATLAB class?
128 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
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 Commenti
Risposte (2)
Daniel Shub
il 24 Set 2012
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 Commenti
Neeraj Rajpurohit
il 30 Giu 2020
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 Commenti
Vedere anche
Categorie
Scopri di più su Methods in Help Center e File Exchange
Prodotti
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!