Raf*_*afe 40
属性只是一种捷径.如果您使用attr_accessor创建属性,Ruby只会声明一个实例变量并为您创建getter和setter方法.
既然你问了一个例子:
class Thing
attr_accessor :my_property
attr_reader :my_readable_property
attr_writer :my_writable_property
def do_stuff
# does stuff
end
end
Run Code Online (Sandbox Code Playgroud)
以下是您使用该课程的方法:
# Instantiate
thing = Thing.new
# Call the method do_stuff
thing.do_stuff
# You can read or write my_property
thing.my_property = "Whatever"
puts thing.my_property
# We only have a readable accessor for my_readable_property
puts thing.my_readable_property
# And my_writable_propety has only the writable accessor
thing.my_writable_property = "Whatever"
Run Code Online (Sandbox Code Playgroud)
Sim*_*tti 31
属性是对象的特定属性.方法是对象的功能.
在Ruby中,默认情况下所有实例变量(属性)都是私有的.这意味着您无法在实例本身范围之外访问它们.访问该属性的唯一方法是使用访问器方法.
class Foo
def initialize(color)
@color = color
end
end
class Bar
def initialize(color)
@color = color
end
def color
@color
end
end
class Baz
def initialize(color)
@color = color
end
def color
@color
end
def color=(value)
@color = value
end
end
f = Foo.new("red")
f.color # NoMethodError: undefined method ‘color’
b = Bar.new("red")
b.color # => "red"
b.color = "yellow" # NoMethodError: undefined method `color='
z = Baz.new("red")
z.color # => "red"
z.color = "yellow"
z.color # => "yellow"
Run Code Online (Sandbox Code Playgroud)
因为这是一个非常commmon行为,Ruby提供了一些方便的方法来定义存取方法:attr_accessor,attr_writer和attr_reader.
| 归档时间: |
|
| 查看次数: |
37608 次 |
| 最近记录: |