Creates a new Torch class called name. If parentName is provided, the class will inherit
parentName methods. A class is a table which has a particular metatable.
If name is of the form package.className then the class className will be added to the specified package.
In that case, package has to be a valid (and already loaded) package. If name does not contain any "=.=",
then the class will be defined in the global environment.
A (meta)table is returned. This table contains all the method provided by the class. After a call to torch.class()
you have to fill-up properly the metatable.
After the class definition is complete, constructing a new class name will be achieved by a call to name().
This call will first call the method __init() if it exists, passing all arguments of name() into
__init().
If parentName has been provided, the class table will also contain the field __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
For advanced users, it is worth mentionning that torch.class() actually calls torch.newmetatable().
with a particular constructor. The constructor creates a Lua table and set the right metatable on it, and then
calls __init() if it exists in the metatable. It also sets a
__factory field such that it is possible to create an empty object of this class.