Classes

While Vim doesn't explicitly contain classes, dictionaries support having methods on them, supporting the object-oriented programming paradigm. There are two ways to define a method on a dictionary.

Given an existing dictionary, animal_names:


let animal_names = {
'cat': 'Miss Cattington',
'dog': 'Mr Dogson',
'parrot': 'Polly'
}

You could do the following to add a method to it:


function animal_names.GetGreeting(animal)
return self[a:animal] . ' says hello'
endfunction

You can now execute the function:


:echo animal_names.GetGreeting('cat')
Miss Cattington says hello

You can use self (just like in Python!) to refer to dictionary keys.

In the previous example, GetGreeting becomes a callable dictionary key. Effectively, animal_names becomes this:

{
'cat': 'Miss Cattington',
'dog': 'Mr Dogson',
'parrot': 'Polly',
'GetGreeting': function <...>
}

For the next example, let's wrap our animal_names dictionary in a slightly more generic animals. This will make our next example behave slightly more like classes we're used to in other languages (and would help us avoid name collisions):

let animals = {
'animal_names' : {
'cat': 'Miss Cattington',
'dog': 'Mr Dogson',
'parrot': 'Polly'
}
}

You can also define a function before having a dictionary ready, by using dict keyword after the function name:


function GetGreeting(animal) dict
return self.animal_names[a:animal] . ' says hello'
endfunction

Now, we'll need to assign the function as another dictionary key:

let animals['GetGreeting'] = function('GetGreeting')

Now, you can call GetGreeting in the same manner:

:echo animals.GetGreeting('dog')
Mr Dogson says hello
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.188.168.28