Chinaunix
标题:
继承与类常量问题
[打印本页]
作者:
jhsea3do
时间:
2008-09-19 23:38
标题:
继承与类常量问题
# reporter.rb
require 'logger'
class Reporter
# Reporter Attributes
attr :bugs
attr :params
# defined statics
@@logger = Logger.new('/tmp/' + self.to_s.downcase + '.log', 'daily')
# Contruct Method
def initialize
begin
@@logger.info('initialize')
rescue
# TODO
end
end
end
class AnotherReporter < Reporter
end
复制代码
当我 Reporter.new 其实和 AnotherReporter.new 时都会写日志文件,但都只会写入到/tmp/reporter.log,
然尔我现在想把AnotherReporter的日志写入一个/tmp/anotherreporter.log,请问这个代码应该如何写?
作者:
sysno
时间:
2008-09-21 15:26
重新定义类变量:
class AnotherReporter < Reporter
@@logger = Logger.new('/tmp/' + self.to_s.downcase + '.log', 'daily')
end
作者:
jhsea3do
时间:
2008-09-23 13:20
恩,我后来试演过
其实不能用@@logger, 一旦设置了该类变量,一旦被其他类继承就会重载这个类变量
class A
@@prop = 'A'
def test
puts @@prop
end
end
class B < A
@@prop = 'B'
end
a = A.new
b = B.new
a.test #=> B
b.test #=> B
作者:
sysno
时间:
2008-09-23 14:42
确实如此,class variable 是会被覆盖的。不好意思,我是初学者。
用类实例变量(class instance variable) 看看这样行不行?
class A
@logger = self.to_s + '.log'
def A.p
puts @logger
end
class B < A
@logger = self.to_s + '.log'
end
A.new.class.p => A.log
B.new.class.p => B.log
作者:
jhsea3do
时间:
2008-09-25 11:52
module M
@@T = ''
def test; puts @@T; end;
def stest; puts self.class::T; end;
end
module N
def rtest; self.class.jtest(); end
end
class A
include M
@@T = 'A'
T = 'sA'
def self.itest; puts T; end
def A.jtest; puts A::T; end
def self.ktest; puts T; end
include N
end
class B
include M
@@T = 'B'
T = 'sB'
def self.itest; puts T; end
def B.jtest; puts B::T; end
def self.ktest; A.ktest; end
include N
end
A.new.test #=> A
B.new.test #=> B
A.new.stest #=> sA
B.new.stest #=> sB
A.itest #=> sA
B.itest #=> sB
A.jtest #=> sA
B.jtest #=> sB
A.ktest #=> sA
B.ktest #=> sA
A.new.rtest #=> sA
B.new.rtest #=> sB
复制代码
作者:
shitou251314
时间:
2008-09-28 22:17
class A
def initialize(log)
#log
end
end
class B < A
def initialize(log)
super(log)
end
end
欢迎光临 Chinaunix (http://bbs.chinaunix.net/)
Powered by Discuz! X3.2