Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Python: modifying class from an inside function

  1. Jun 11, 2013 #1
    I feel very stupid right now. Should be an easy question, but I googled it to no avail.
    Basically, I have an class.object in my code which should be managed by a class.function
    For example, I want the following code:

    Code (Text):
    class Z:
            def mod(self):

    print Z.a
    print Z.a
    print Z.a
    to return "0 1 2", instead of "0 0 1"
    Can it be done in Python? If yes, what is the Python way of doing so? If no, why not?
    Last edited: Jun 11, 2013
  2. jcsd
  3. Jun 11, 2013 #2


    User Avatar
    Science Advisor

    I think you have several things wrong.
    First, inside the mod function, I think you should have: self.a = self.a + 1
    Second, when you create the object t as an instance of class Z, you should have: t = Z()
    This invokes the constructor of Z.
    Third, when you call the function mod you should have: t.mod()
    Fourth, don't you want print t.a instead of print Z.a ??
  4. Jun 11, 2013 #3
    Oh, I'm so sorry, was writing it in a hurry!
    Yes, it's working right now, thanks!
    I think that my face is quite red now.
  5. Jun 11, 2013 #4
    Also, you need to keep in mind the difference between a class and an instance of it...class Z is already an object in its own right that can be dealt even before creating the instance t...so, you actually have 2 things going on and you need to learn how to deal with them....you have class attributes and instance attributes...go back and re-read classes...
  6. Jun 11, 2013 #5
    Code (Text):
    ## @file static.py
    import sys

    class Z: # declares a "class object"
        a = 0 # inited when Z is seen first
        def mod():
            Z.a += 1

    t = Z # t is an alias reference on the Z "class object"
    sys.stderr.write('\t' + str(t) + '\n')

    t.a += 1

    u = Z() # u is a Z instance
    sys.stderr.write('\t' + str(u) + '\n')

    u.mod() # actually works, contrary to C++ or Java statics!
    sys.stderr.write('\t' + str(Z.a) + '\n')
    Code (Text):
    python static.py
    Code (Text):
        <__main__.Z instance at 0x7f5233334488>
    Tested with python 2.7 and python 3.1 on x86_64 Debian "squeeze" Linux

    Regards, S.

    P.S.: Pls keep in mind that "print" without brackets is outdated.
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook