oop - Lua类继承问题

标签 oop class inheritance lua multiple-inheritance

我有两个 Lua 类。一个继承了另一个。

test1 = {test1Data = 123, id= {0,3}}
function test1:hello()
    print 'HELLO!'
end
function test1:new (inp)
    inp = inp or {}
    setmetatable(inp, self)
    self.__index = self
    return inp
end
test2 = {}
function test2:bye ()
    print ('BYE!', self.id)
end
function test2:new_inst_test (baseClass, inp)
    inp = inp or {}
    setmetatable(inp, self)
    self.__index = self
    if baseClass then
        setmetatable( inp, { __index = baseClass } )
    end
    return inp
end

a = test1:new({passData='abc1'})
b = test1:new({passData='ghyrty'})

c = test2:new_inst_test(a,{temp = '123343321135'})
d = test2:new_inst_test(b, {temp = '1'})



print (c.temp, c.test1Data, c.passData)
print (d.temp, d.test1Data, d.passData)
c:bye()
c:hello()

我希望 test2 不仅继承 test1,而且保存自己的方法('再见')。 是否可以? 谢谢!

最佳答案

我认为你应该在类元表上设置一个带有 __index=baseclass 的元表。但这将更改 test2 类中所有对象的元表。通过这种方式,您将使用类本身的方法,并且仅当当前类中不存在该方法或者该方法是元表时才使用父级的方法。

所以应该是这样的

if baseClass then
    setmetatable( self, { __index = baseClass } )
end

另一方面,您只在创建新实例时指定基类,而不是在创建新类时指定它,这有点奇怪。 所以我会重新考虑如何在类之间继承,而不是在实例和类之间继承。

作为一个以魔法为主题的小示例:

--oop.lua Example of OOP and inheritance in Lua
Person={
    age=0,
    className='Person'
}
-- needed if needed add comparisons, operations, ...
mtPerson={}
mtPerson.__index={
    getClassName=function(self)
        return self.className
    end,
    new=function(self,t)    
        return setmetatable(t or {},{__index=self})
    end,
    inherit=function (self,t,methods)
        -- This is the heart of the inheritance: It says:
        -- Look it up in the methods table, and if it's not there, look it up in the parrent class (her called self)
        -- You pass this function the parent class (with :), a table of attributes and a table of methods.
        local mtnew={__index=setmetatable(methods,{__index=self})}
        return setmetatable(t or {},mtnew)
    end,
    introduce=function(self)
        print(("Hi! I'm %s, I'm a %s and I'm %d years old"):format(self.instanceName,self.className,self.age))
    end
    }

setmetatable(Person,mtPerson)

-- Wizard inherits from the class Person, and adds some default values and methods
Wizard=Person:inherit({
    className="Wizard",
    knownSpells={},
    },
    {
    listSpells=function(self)
        print("known spells:",self)
        if #self.knownSpells==0 then
            print'none'
        else
            for k,v in ipairs(self.knownSpells) do
                print(k,v)
            end
        end
    end
    }
)

i1=Person:new{
    inventory={'wallet'},
    instanceName="John",
}

i2=Wizard:new{ -- inherited method "new"
    inventory={'wallet','wand','cloak of invisibility'},
    instanceName="Harry",
    age=20,
    knownSpells={'Avada kavedra', 'Sesame open'}
}

i1:introduce() -- inherited method "introduce" notice that qge is the default value of 0
i2:introduce() -- 

i2:listSpells() -- method only in class 2
i1.age=26
i1:introduce()    -- changed age of instance
print(Person.age)    -- didn't change class defaults
print(Wizard.age)
i1:listSpells() -- Error.

在写这篇文章时,我得出的结论是 Lua 中的 OOP 既非常简单,又非常复杂。您只需要在编写代码之前真正考虑清楚,然后坚持计划即可。因此,在这里我选择将属性放在类和实例表本身中,并将所有方法放在各自的元表中。我这样做是因为现在可以很容易地遍历所有属性,而无需遇到方法,但任何有效的选择都是有效的。您只需选择一个即可。

关于oop - Lua类继承问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6927364/

相关文章:

javascript - 在工厂类中实现继承,而无需在 Javascript 中复制代码

php - 如何从发货ID或观察者处获取订单ID?

python - 全局变量如何/为什么可用/在嵌套类实例的范围内,但 "nonlocal"变量不可用?

ios - 设置时更改类属性

C++ 覆盖父结构中的数据不起作用

c++ - 有没有办法在继承类的基类中指定数组的大小?

inheritance - TablePerHierarchy 对于抽象类总是 false?

java - 从 Java 中的一个大 JSON 中仅提取一行

python - 在 python 中创建一个可重用的类

sql - 设计 SQL 数据库来表示 OO 类层次结构