我知道在類實例中,我應該通過實例變量讀取變量的值。 但是通過自我閱讀的後果是什麼?使用self讀取實例變量
見下面的例子:
class Test attr_writer :aa
def testing
puts @aa
puts self.aa <-- what are the consequences if I apply attr_reader :aa and try to read 'aa' via self.aa ? can I read other value by accident?
end
def self.bb
a = self.new
a.aa = "111"
a.testing
end
end
Test.bb
'puts self.aa'與'puts aa'相同。這是因爲'self'是默認的接收器。由於'testing'是一個實例方法,它被'Test'的一個實例調用,所以'self'等於方法中的實例。您可以通過在方法中添加'puts「self =#{self}」'來確認。 'puts aa'(或'puts self.aa')的效果取決於您是否創建了'aa'的訪問器(例如'attr_reader:aa')。如果有的話,'puts aa'會通過訪問器給出@aa的值;如果你沒有,會引發異常,通知你沒有局部變量或方法'aa'。 –
好的,任何特定的原因:「但是由於各種原因,建議使用該方法而不是@variable。」 ? –