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 Exchange에서 Handle 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