What is the variable 'self' in MATLAB class?

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 !

回答 (2 件)

Daniel Shub
Daniel Shub 2012 年 9 月 24 日

2 投票

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 ...
Neeraj Rajpurohit
Neeraj Rajpurohit 2020 年 6 月 30 日

0 投票

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

カテゴリ

ヘルプ センター および File ExchangeHandle Classes についてさらに検索

製品

質問済み:

2012 年 9 月 24 日

回答済み:

2020 年 6 月 30 日

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by