• 面向对象


    --对于一个对象来说,是有属性和方法的
    
    person = {name = "chenquanlong",age=18};
    
    --第一种
    --[[
    person.eat = function()
      print(person.name.."在吃饭")
    end
    --]]
    
    --当使用:定义一个值的时候,我们可以在这个方法里面使用self
    
    function person:eat()
      print(self.name.."在吃饭")
    end
    --person.eat(person)等价于person:eat()
    --在使用面向对象的时候使用:来实现方法
    --当通过:调用的时候,系统会自动传递当前table给self,当通过.来调用方法的时候,self不会自动赋值,我们必须通过第一个参数来传递当前的table
    
    --构造
    --lua无法像C#一样去定义一个对象,在lua里面我们可以先做一个原型,这个原型是不作为实际使用的
    --作为整个table的原型,根据这个原型去创建新的表,即对象
    Person = {name = "chenquanlong",age=18};
    function Person :eat()
      print(self.name.."在吃饭")
    end
    --通过下面的方法去获得一个新表
    function Person:new(tab)
      local t = tab or {};
      setmetatable(t,{__index = self})
      return t;
    end
    
    person1 = Person:new(nil);
    person2 = Person:new(nil);
    person1:eat();
    
    --继承
    --上面由person原型 ,person1和person2继承person
    Student = Person:new();
    student1=Student:new();
    student1:eat();
    

      

  • 相关阅读:
    CF600E Lomsat gelral 题解
    特征工程高级特征开发
    mysql 实现 TOP n
    python调用百度的情感分析API过程
    使用python建立ARIMA模型
    PYTHON 提取HTML文本
    推荐算法架构
    python json 格式化 打印
    教你用PyTorch部署模型的方法
    python 精准 四舍五入方法
  • 原文地址:https://www.cnblogs.com/xingyunge/p/10936300.html
Copyright © 2020-2023  润新知