ruby instance variable in python

Steven D'Aprano steve+comp.lang.python at pearwood.info
Mon Oct 6 14:54:17 EDT 2014


roro codeath wrote:

> in ruby:
> 
> module M
> def ins_var
> @ins_var ||= nil
> end
> 
> def m
> @ins_var = 'val'
> end
> 
> def m2
> m
> ins_var # => 'val'
> end
> end


I admit that my Ruby skills are admittedly pretty lousy. Still, I used to
think that Ruby was pretty readable, but I find the above completely
meaningless. So I'm going to guess what you want, sorry if I guess wrong.


> in py:
> 
> # m.py
> 
> # how to def ins_var
> 
> def m:
>     # how to set ins_var
> 
> def m2:
>     m()
>     # how to get ins var


Please explain what you mean by "instance variable". There are two standard
things which it could be.

(1) A string variable is a variable holding a string. A float variable is a
variable holding a float. A list variable is a variable holding a list. So
an instance variable must be a variable holding an instance.

ins_var = NameOfTheClass(arg)

You just instantiate the class, passing whatever arguments it expects.

(2) In the Java world, "instance variable" doesn't mean a variable at all,
but an attribute of classes which is stored on the instance. (As opposed to
those attributes stored on the class itself, which they refer to
as "static", since in Java they are known to the compiler.)

To define "instance variables" (attributes), you have to have a class to
define them in. Remember that Python uses the "Offside Rule" (significant
indentation).

class MyClass(object):  # subclass of object
    def __init__(self, arg):
        # Initialise the instance.
        self.ins_var = arg
    def method(self, arg):
        return self.ins_var == arg:
 

instance = MyClass("some value")
print(instance.ins_var) # prints "some value"
instance.method("spam and eggs")  # returns False
instance.method("some value")  # returns True


Does this help?



-- 
Steven




More information about the Python-list mailing list