作者godfat (godfat 真常)
看板Ruby
标题Re: [问题] 相同的instance和class method
时间Tue May 11 18:04:11 2010
※ 引述《ihower (好2ˇ)》之铭言:
: 是指 instance method 跟 class method 一样吗? XD
: def price
: self.class.price
: end
: def self.price
: ...
: end
[...]
: 推 godfat:不建议这样设计,很混淆 05/10 22
: 推 bypang:godfat大大有何建议吗?一个是virtual attributes 05/11 12
: 推 bypang:一个是class method,可是都有相同的code 05/11 12
: → godfat:看起来不像是 virtual attribute,而是class method wrapper 05/11 15
我在 facebooker 里面看到不少类似的用法,这让我感到很混淆,
因为我会搞不清楚当我看到 Item.price 和 Item.new.price 之间的差别是什麽?
翻了 source code 之後才发现其实根本一样。
我觉得所谓 instance method, 就是为了存取 instance variable.
觉得打 item.price 或是 Item.price 或是 item.class.price 应该也没省几个字吧?
但是两者混用时,乍看之下还真不知道有什麽差别。
我会假设 item.price 会根据某个东西,比方说,某些 item 有打折,
而 Item.price 则是某种定价,不会根据不同 item 而有所改变的。
这边只是随便举例,我想说的是,就打 Item.price 并没有那麽难...
多个 instance method 去呼叫 class method 没什麽必要。
--
#!/usr/bin/env ruby [露比] /Programming (Kn|N)ight/ 看板《Ruby》
# if a
dog nailed
extra legs that
http://webptt.com/cn.aspx?n=bbs/Ruby/index.html
#
walks like an octopus, and Welcome ~
Ruby@ptt~
#
talks like an octopus, then
◢█◣ http://www.ruby-lang.org/
# we are happy to treat it as
█ http://www.ruby-doc.org/
# if it were
an octopus.
◥ ◤ http://www.rubyforge.org/
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 118.168.130.55
1F:推 poga:我也不喜欢这种作法... 有啥特别适合的例子吗XD? 05/13 05:21