当前位置 博文首页 > Ruby简洁学习笔记(二):类继承、属性、类变量

    Ruby简洁学习笔记(二):类继承、属性、类变量

    作者:admin 时间:2021-02-11 15:29

    1.如何声明一个子类

    复制代码 代码如下:

    class Treasure < Thing

    这样Thing类中的属性name,description都被Treasure继承

    2.以下三种方式传入父类initialize方法的参数分别是什么?

    复制代码 代码如下:

    # This passes a, b, c to the superclass
    def initialize( a, b, c, d, e, f )
      super( a, b, c )
    end
    # This passes a, b, c to the superclass

    def initialize( a, b, c )
      super
    end
    # This passes no arguments to the superclass
    def initialize( a, b, c)
      super()
    end

    第一种把参数中a,b,c传入父类initialize方法;第二种传入全部参数,但不加上括号;第三种不传入参数

    3.属性的setter/getter

    有人这样写setter/getter:

    复制代码 代码如下:

    puts( t1.get_description )
    t1.set_description( “Some description” )

    这样似乎更方便一些:
    复制代码 代码如下:

    puts( t1.description )
    t1.description = “Some description”

    如果你想用第二种写法,你不得不这么写:

    注:这是正确的:def name=(aName)

    但这却是错的:def name  =(aName)

    你看出差别的了吗?

    根据上一章,你可以知道,这里定义了两个方法:description方法和description=方法。原来是通过将"="加入方法名实现的,ruby真是神奇,Java就不能这样写。

    然而,事实上有更简单的方法来实现setter/getter

    复制代码 代码如下:

    attr_reader :description
    attr_writer :description

    由一个attr_reader/attr_writer加上符号(:description)构成,事实上,可以一次为多个元素设置setter/getter
    复制代码 代码如下:

    attr_writer(:name, :description)
    attr_accessor(:value, :id, :owner)
    attr_accessor

    等价于:
    复制代码 代码如下:

    attr_reader :value
    attr_writer :value

    4.super

    和Java不一样,Ruby中的super方法可以出现在任何方法中,而不只是initialize(构造方法)中。

    在第2点中就对super方法的使用有介绍,单独的super将所有参数传给父类initialize,而带参数的super则将指定参数传给父类initialize。

    复制代码 代码如下:

    # This passes aName, aDescription to the superclass
    def initialize( aName,aDescription )
      super( aName, aDescription )
    end

    # This passes a, b, c to the superclass's aMethod
    def aMethod( a, b, c )
      super
    end

    5.常量和嵌套类(constants & nested class)

    复制代码 代码如下:

    class X
     A = 10
     
     class Y
      def xyz
       puts( "goodbye" )
      end
     end
     
     def self.abc
      puts("hello")
     end
    end

    常量:以大写字母开头的变量。

    如果要访问常量或内部类,需用 ::

    复制代码 代码如下:

    puts( X::A )
    X::abc        # 你也可以用::来调用方法
    X.abc        # 当然这样也可以

    ob = X::Y.new
    ob.xyz

    6.部分类(Partial Class)

    在Ruby中可以对现存的类进行修改,并影响已经生成的对象

    复制代码 代码如下:

    class A
      def a
        puts 'a'
      end
    end

    a = A.new
    a.public_methods(false)//打印A class所有public的方法
    # => [:a] //只有a

    class A
      def b
        puts 'b'
      end
    end

    a.public_methods(false)
    # => [:a, :b]//有a和b

    而不能修改的,是类继承了哪个类。比如

    复制代码 代码如下:

    class A
      def a
        puts 'a'
      end
    end

    class A < String
      def c
        puts 'c'
      end
    end

    # TypeError: superclass mismatch for class A
    # 所有类默认继承了Object类,A也继承了Object,所以当你让A继承String时就会报错

    js
    下一篇:没有了