Erik Max Francis wrote:
> Note this only changes the attribute in the instance.  If he wants it to
> be changed for all other instances, he needs to change it in the class
> with:: A._var1 = 1

Yes, but in the OP's code func1() is called by __init__ for every
instance - which in fact makes declaring _var1 as a class attribute
useless

Anyway, I find that changing the class attribute by calling a method on
an instance is a little confusing. I would rather set the class
attribute like this :

class A2:

     _var1 = 0

     def getvarValue(self):
         return self._var1

a = A2()
print a.getvarValue()
>>> 0
A2._var1 = 0  # change class attribute
print a.getvarValue()
>>> 1
b = A2()
print b.getvarValue()
>>> 1

Or using a class method :

class A3:

    _var1 = 0

    @classmethod
    def func1(cls):
        cls._var1 = 1

    def getvarValue(self):
        return self._var1

a = A3()
print a.getvarValue()
>>> 0
A3.func1() # change class attribute
print a.getvarValue()
>>> 1
b = A3()
print b.getvarValue()
>>> 1

Pierre

-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to