Ruby 这句话看不懂,求助

levan · 2012年04月19日 · 最后由 fsword 回复于 2012年04月24日 · 2495 次阅读

When you design a class, you decide what internal state it has and also decide how that state is to appear on the outside (to users of your class). The internal state is held in instance variables. The external state is exposed through methods we’re calling attributes. And the other actions your class can perform are just regular methods. It really isn’t a crucially important distinction, but by calling the external state of an object its attributes, you’re helping clue people in to how they should view the class you’ve written.

匿名 #1 2012年04月19日

按照我的理解,简单来说就是隐藏内部状态,然后设计好直观的 api 吧

匿名 #2 2012年04月19日

And the other actions your class can perform are just regular methods. It really isn’t a crucially important distinction, but by calling the external state of an object its attributes, you’re helping clue people in to how they should view the class you’ve written. 类表现出的相似的功能应该设计成相似的调用方法,这样调用者使用会更方便。应该就这意思

@jjym 哦,谢谢~

当你设计一个类的时候,你决定它的内部状态,并且也决定这个状态在外部(你的类的使用者们)看来是什么样的。内部的状态由实例变量持有。而外部的状态则通过方法暴露出来,我们称这些方法为属性。而你的类能够执行的其他行为,则是常规的方法。这个区别也不是真的特别重要,但把一个对象的外部状态称为它的属性,可以让别人容易弄清楚你写的类。

就是属性(attributes)与实例变量(instance variables)的概念区别。

匿名 #5 2012年04月19日

#4 楼 @dotnil

  • -!! 英语三级的悲剧啊..第二句我完全理解错了

真想找个 ROR 的导师。。。交几百块学费都行。。。

呃,我的理解是,你设计类的时候,要把不该给人看的藏好,要给人用的写 accessors(getter, setter)来给人使用。比如你的类 Person 里面有一个变量 height,就可以定义

# getter def height return @height end

#setter def height=(new_height) @height = new_height end

让人存取,而不是让人直接来存取,这也就是 OO 里面的封装。。。

@Juanito 通俗易懂,谢谢~~~~~~

#10 楼 @Levan 你可以花時間看看 Agile Web Development with Rails 的第四章,但是主要還是得看那本 1000 頁的 Programming Ruby...

@Juanito 我在看 Programming Ruby1.9 上面那段就是来自那里的,有点绕看不懂。那本书主要内容是四百多页吧,后面是些参考,想着这个月尽量看完 Ruby,然后下个月开始看 Agile Web Development with Rails。英文一般,慢慢练习这方面的阅读速度吧。Thank you for your help!

@Juanito 微博给了你条私信,麻烦看看好吗?

#13 楼 @Levan 呃,我看了,我自己也是刚学习 Rails,无法当你的导师啊。建议不浮躁慢慢看书,相信 ruby-china.org 上面这么多朋友、大牛都能给你帮助。。。

@Juanito 好的~也是,自己太浮躁了。。。Thx~

我怎么理解成封装性了

当你设计一个类的时候,你需要考虑它有哪些内部状态,以及它是如何将这些(内部)状态表现给外界(这个类的“用户”)的。负责记录内部状态的就是实例变量。而所谓外部状态,就是用对象的方法来暴露给外界的结果(为了便于区分,这类方法我们称之为“属性”,除此以外的方法称为一般方法)。这两种状态其实并不需要特别严格的留意,但是用“外部状态”这个词可以告诉人们,这是(你设计的)那个类的对外“表现”(而不是内部实现)

......累死了,以后翻译的事情要谨慎

需要 登录 后方可回复, 如果你还没有账号请 注册新账号