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)
我想知道为什么会发生这个错误。
这解决了问题。但是,你能告诉我为什么'self .__ parent'不起作用吗?谢谢! –
这是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)返回的父类metatable进行交互。 – deltheil