python class confusion

February 18th, 2008
[ Geek ]

I’m sure this is explained quite clearly somewhere like here or here. Hopefully someday I’ll be pythonic enough to understand. In the meantime, this is confusing to me and a bit scary. I’m hoping someone can explain to me why I’d want this behaviour.

Let’s take a really simple class with one method. All that method does is creates a variable local to that method and then print it out. One catch, first I call a second method, passing in that variable, and change it within the scope of that second method. As expected, that has no impact on the variable in the calling method and the result when you run it is “local…”

class klass(object):
    def settime(self, s):
        s=’remote’

    def dosomething(self):
        astring=’local’
        self.settime(astring)
        print “%s…” % astring

if __name__ == “__main__”:
    c = klass()
    c.dosomething()

Modify the above, adding a class within that same method call, again attempting to modify it in the second method call. Again, do nothing more than print both variables out. My instincts do NOT have me expecting the results I get, which are “local remote…”

class me(object):
    def __init__(self, n):
        self.name=n

class klass(object):
    def settime(self, t, s):
        t.name=’remote’
        s=’remote’

    def dosomething(self):
        astring=’local’
        aclass=me(‘local’)

        self.settime(aclass, astring)
        print “%s %s…” % (astring, aclass.name)

if __name__ == “__main__”:
    c = klass()
    c.dosomething()

No, these aren’t my typical naming conventions.