2016-05-22 2 views
2

Вопрос состоит из torch5 урока: http://torch5.sourceforge.net/manual/torch/index-8-1.htmlLua, попытка '__parent' индекс поля (нилъ значение)

require "torch" 

-- for naming convenience 
do 
    --- creates a class "Foo" 
    local Foo = torch.class('Foo') 

    --- the initializer 
    function Foo:__init() 
    self.contents = "this is some text" 
    end 

    --- a method 
    function Foo:print() 
    print(self.contents) 
    end 

    --- another one 
    function Foo:bip() 
    print('bip') 
    end 

end 

--- now create an instance of Foo 
foo = Foo() 

--- try it out 
foo:print() 

--- create a class torch.Bar which 
--- inherits from Foo 
do 
    local Bar = torch.class('torch.Bar', 'Foo') 

    --- the initializer 
    function Bar:__init(stuff) 
    --- call the parent initializer on ourself 
    self.__parent.__init(self) 

    --- do some stuff 
    self.stuff = stuff 
    end 

    --- a new method 
    function Bar:boing() 
    print('boing!') 
    end 

    --- override parent's method 
    function Bar:print() 
    print(self.contents) 
    print(self.stuff) 
    end 
end 

--- create a new instance and use it 
bar = torch.Bar("ha ha!") 
bar:print() -- overrided method 
bar:boing() -- child method 
bar:bip() -- parent's method 

После запуска этого сценария, я получил сообщение об ошибке:

/Users/frankhe/torch/install/bin/luajit: test1.lua:39: attempt to index field '__parent' (a nil value) 

Вот изображение деталей: enter image description here

Я хочу знать, почему эта ошибка произошла.

ответ

1

Использование:

local Bar, parent = torch.class('torch.Bar', 'Foo') 

И:

function Bar:__init(stuff) 
    parent.__init(self) 

    self.stuff = stuff 
end 
+0

Это решает проблему. Однако не могли бы вы сказать мне, почему «я .__ родитель» не работает? Спасибо! –

+1

Вот как работает система класса torch7: см. Эту [документацию] (https://github.com/torch/torch7/blob/master/doc/utility.md). Нет такого поля '__parent'. Вместо этого вы напрямую взаимодействуете с метатебельным родительским классом, который возвращается ['torch.class'] (https://github.com/torch/torch7/blob/master/init.lua#L104-L107). – deltheil

Смежные вопросы