How do I declare global vars or class vars in Python ?

Nick Craig-Wood nick at craig-wood.com
Fri Feb 20 06:31:54 EST 2009


Linuxguy123 <linuxguy123 at gmail.com> wrote:
>  How do I do this in Python ?
> 
>  #############################
>  declare A,B
> 
>  function getA
>      return A
> 
>  function getB
>      return B
> 
>  function setA(value)
>       A = value
> 
>  function setB(value)
>       B = value
> 
>  main()
>      getA
>      getB
>      dosomething
>      setA(aValue)
>      setB(aValue)
>  ############################
> 
>  The part I don't know to do is declare the variables, either as globals
>  or as vars in a class.  How is this done in Python without setting them
>  to a value ?

Variables can have any value in python so if you want to pre-declare
then you set them to None normally.

As a class :-

class Stuff(object):
    def __init__(self):
        self.A = None
        self.B = None
    def getA(self):
        return self.A
    def getB(self):
        return self.B
    def setA(self, value):
        self.A = value
    def setB(self, value):
        self.B = value

>>> a = Stuff()
>>> print a.getA()
None
>>> print a.getB()
None
>>> # dosomething
... a.setA("aValue")
>>> a.setB("aValue")
>>> print a.getA()
aValue
>>> print a.getB()
aValue
>>> 

Note that in python we don't normally bother with getA/setA normally,
just use self.A, eg

class Stuff(object):
    def __init__(self):
        self.A = None
        self.B = None
    def main(self):
        print self.A
        print self.B
        # dosomething
        self.A = "aValue"
        self.B = "aValue"
        print self.A
        print self.B

>>> a = Stuff()
>>> a.main()
None
None
aValue
aValue
>>>  

If you need (later) A to be a computed value then you turn it into a
property, which would look like this.  (Note the main method is
identical to that above).

class Stuff(object):
    def __init__(self):
        self._A = None
        self.B = None
    def _getA(self):
        print "Getting A"
        return self._A
    def _setA(self, value):
        print "Setting A"
        self._A = value
    A = property(_getA, _setA)
    def main(self):
        print self.A
        print self.B
        # dosomething
        self.A = "aValue"
        self.B = "aValue"
        print self.A
        print self.B

>>> a = Stuff()
>>> a.main()
Getting A
None
None
Setting A
Getting A
aValue
aValue
>>>  

-- 
Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick



More information about the Python-list mailing list