ruby的类是单继承生物、所以出现了module、实现了多继承、
注:模块、常量和类的命名都是以大写字母开头
、 模块引用:
1、如果引用的模块在同一个文件中,则直接使用模块操作
2、如果不在同一个文件中,则需要使用require加载被引用模块所在文件。(引用的是完整名称)
可以使用module包含着各种class、再新建一个类使用include包含各种class、从而实现多重继承、=。 =真是复杂的生物、想简单点觉得变和更复杂了、
其实modeule不是能够被实例化的、所以只能通过module.method这样来引用方法、当然首先得来一句
- instance_method :fun1
- Ruby提供了public、protected和private来修饰类成员,其含义与C++相同。但不同的是,在Ruby中,所有类变量都默认 是private的,而类函数都默认是public的。对类成员而言,也可像第4行那样用attr_accessor对其进行修饰,使其可被外部访问。
类包括多个模块
- module Mod1
def fun1
puts "Mod1::fun1"
end
instance_method :fun1
end
module Mod2
def fun2
puts "Mod2::fun2"
end
instance_method :fun2
end
class Cls
include Mod1
include Mod2
end
obj = Cls.new
obj.fun1
obj.fun2
模块包含类
- module Mod
def myFunction
puts "myFunction"
end
module_function :myFunction
class Class
def yourFunction
puts "Mod::Class.yourFunction"
end
end
end
Mod.myFunction
object = Mod::Class.new
object.yourFunction
假如module定义下以下的方法
- module MyModule
GOODMOOD = "happy"
BADMOOD = "grumpy"
def greet
return "I'm #{GOODMOOD}. How are you?"
end
def MyModule.greet
return "I'm #{BADMOOD}. How are you?"
end
end
其中的MyModule.greet方法、等同于
- def self.greet
return "I'm #{BADMOOD}. How are you?"
end
这里定义的常量可以使用以下方法来访问
- MyModule::GOODMOOD
某天迩想引用一下greet方法时、可以使用
- MyModule.greet
但是若果迩觉得烦琐、可以先include该模块先
- include MyModule
puts( greet )
注意一下、使用include方法这仅仅只是引用greet方法、而非MyModule.greet、模块自己的方法只能由模块名称引出、无法使用include方法替迩减少些打字的痛苦、
承接上面的例子、写了一个类、引用上面的模组、没错啦!这就是RUBY多承继承的实现方法 !
- class MyClass
- include MyModule
- def sayHi puts
- (greet)
- end
- end
在类中用include包含了上面的模组、好吧、莪们实例化一下
- ob = MyClass.new
ob.sayHi
puts(ob.greet)
可以惊奇的发现、居然类的实例对象也可以访问模组的实例方法、太神奇了、相当于已经继承了模组的所有方法
下面再来个多重继承的范例
- module MagicThing
attr_accessor :power
end
module Treasure
attr_accessor :value
attr_accessor :owner
end
class Weapon
attr_accessor :deadliness
end
class Sword < Weapon
include Treasure
include MagicThing
attr_accessor :name
end
从上面看、设置了多个模组、MagicThing和Treasure、还有一个Weapon的类、它们统统都在Sword的继承中实现啦~ 首先Sword继承了Weapon、然后再用include引入了两个模组、所以下面的实现方法是完全成立的!
- s = Sword.new
s.name = "Excalibur"
s.deadliness = "fatal"
s.value =
s.owner = "Gribbit The Dragon"
s.power = "Glows when Orcs Appear"
下面莪们来关注一下模块里头的变量、注意一点、模块里的本地变量是无法被模块外所调用的、甚至是return都不可以、这就是为什么模组内部实例变量满天飞的原因了
- x = # local to this program
module Foo
x = # local to module Foo
# This can be mixed in but the variable x won't then be visible
def no_bar
return x
end
def bar
@x =
return @x
end
puts("In Foo: x = #{x}") # this can access the „module local‟ x
end
include Foo
puts(x)
#puts(no_bar) # Error! This can't access the module-local variable
## needed by the no_bar method
puts(bar)
可以看到莪已经屏蔽了第24行的代码、因为这个方法是错误的!不能够被调出去、
以上就是模块全解======>>ruby的类是单继承生物、所以出现了module、实现了多继承的详细内容,更多关于模块全解======>>ruby的类是单继承生物、所以出现了module、实现了多继承的资料请关注九品源码其它相关文章!