Assuming a module is included, not extended, what's difference between module instance variable and class variable?
I do not see any difference between two.
module M
@foo = 1
def self.foo
@foo
end
end
p M.foo
module M
@@foo = 1
def self.foo
@@foo
end
end
p M.foo
I have been using @ as @@ within a module, and I recently saw other codes are using @@ within a module. Then I thought I might have been using it incorrectly.
Since we cannot instantiate a module, there must be no difference between @ and @@ for a module. Am I wrong?
----------------------- added the following --------------------
To answer some of questions on comments and posts, I also tested the following.
module M
@foo = 1
def self.bar
:bar
end
def baz
:baz
end
end
class C
include M
end
p [:M_instance_variabies, M.instance_variables] # [@foo]
p [:M_bar, M.bar] # :bar
c = C.new
p c.instance_variables
p [:c_instance_variabies, c.instance_variables] # []
p [:c_baz, c.baz] :baz
p [:c_bar, c.bar] # undefined method
When you include a module within a class, module class variables and class methods are not defined in a class.
Modules in Python can be of two types: Built-in Modules. User-defined Modules.
A module is a file containing Python code. A package, however, is like a directory that holds sub-packages and modules.
If you have a problem that you can solve in a very general way, so that the resulting code would be useful in many other programs, put it in its own module.
There are actually three different ways to define a module in Python: A module can be written in Python itself. A module can be written in C and loaded dynamically at run-time, like the re (regular expression) module. A built-in module is intrinsically contained in the interpreter, like the itertools module.
Class variables can be shared between modules and classes where these modules are included.
module A
@@a = 5
end
class B
include A
puts @@a # => 5
end
Meanwhile, instance variables belong to self
. When you include module A
into class B
, self
object of A
is not the same as self
object of B, therefore you will not be able to share instance variables between them.
module A
@a = 5
end
class B
include A
puts @a # => nil
end
@@ refers to class variable and @ refers to instance variable. While using this with module makes big difference. When you include a module you add class methods to your class while extending add instance methods to your class
Following is a nice article on this
http://railstips.org/blog/archives/2006/11/18/class-and-instance-variables-in-ruby/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With