WoNáDo
3/13/2005 5:31:00 PM
--
Wolfgang Nádasi-Donner
wonado@donnerweb.de
"Florian Gross" <flgr@ccan.de> schrieb im Newsbeitrag
news:39gq83F620eslU2@individual.net...
> Lionel Thiry wrote:
>
> > class Test
> > @a = "value"
> >
> > def self.a
> > @a
> > end
> >
> > def initialize
> > @@a = "value2"
> > end
> >
> > def a
> > @@a
> > end
> > end
> >
> > puts Test.a # output: value
> > puts Test.new.a # output: value2
> >
> > I don't understand (and I'm quite surprised), what is the difference in
> > terms of OO design between class variables, the @@a in the example
> > above, and class instance variables, the @a in the example?
>
> Currently class variables are also shared between different classes that
> are part of the same inheritance tree. IMHO this is a rarely needed
> feature and you're better off using regular instance variables on the
> class (and referring to them via self.class.var from an instance).
Where is this described? - It is dangerous if one doesn't know this.
>>> Example >>>
class Animal
@@born = 0
def initialize
@@born += 1
puts "a new animal"
end
def Animal.born
@@born
end
end
class Dog<Animal
@@born = 0
def initialize
@@born += 1
puts "a new dog"
end
def Dog.born
@@born
end
end
class Cat<Animal
@@born = 0
def initialize
@@born += 1
puts "a new cat"
end
def Cat.born
@@born
end
end
print "#{Cat.born} cats, #{Dog.born} dogs, #{Animal.born} animals\n"
2.times{Dog.new}
print "#{Cat.born} cats, #{Dog.born} dogs, #{Animal.born} animals\n"
3.times{Cat.new}
print "#{Cat.born} cats, #{Dog.born} dogs, #{Animal.born} animals\n"
>>> Output >>>
0 cats, 0 dogs, 0 animals
a new dog
a new dog
2 cats, 2 dogs, 2 animals
a new cat
a new cat
a new cat
5 cats, 5 dogs, 5 animals
>>> End of Example >>>