问题描述
我看到如下代码:
class Person
def initialize(name)
@name = name
end
end
我知道这可以让我做person = Person.new
之类的事情,并且可以像其他方法一样在类中的其他地方使用@name
.然后,我看到了类似的代码:
I understand this allows me to do things like person = Person.new
and to use @name
elsewhere in my class like other methods. Then, I saw code like:
class Person
attr_accessor :name
end
...
person = Person.new
person.name = "David"
这两种方法使我无所适从. def initialize(name)
有什么特殊用途?我想attr_accessor
允许我读写.这意味着它们是两种单独的方法.是的?想要澄清def initialize
和attr_accessor
以及它们如何啮合.
I'm just at a loss with these two methods mesh. What are the particular uses of def initialize(name)
? I suppose attr_accessor
allows me to read and write. That implies they are two separate methods. Yes? Want clarifications on def initialize
and attr_accessor
and how they mesh.
推荐答案
initialize
和attr_accessor
彼此无关. attr_accessor :name
创建两种方法:
initialize
and attr_accessor
have nothing to do with each other. attr_accessor :name
creates a couple of methods:
def name
@name
end
def name=(val)
@name = val
end
如果要在创建对象时设置名称,则可以在初始化程序中进行设置:
If you want to set name upon object creation, you can do it in the initializer:
def initialize(name)
@name = name
# or
# self.name = name
end
但是您不必这样做.创建后,您可以稍后设置名称.
But you don't have to do that. You can set name later, after creation.
p = Person.new
p.name = "David"
puts p.name # >> "David"
这篇关于在一个类中将attr_accessor和一个initialize方法混合在一起的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!