Python constructor syntax

Discussion in 'Mac Programming' started by Analog Kid, Feb 22, 2012.

  1. macrumors 68030

    Analog Kid

    Joined:
    Mar 4, 2003
    #1
    Can someone explain why this is behaving how it is:


    Code:
    class TestClass(object):
        def __init__(self,x):
                if isinstance(x,TestClass):
                        self.x=x.x
                else:
                        self.x=x
        def foo(self,y):
                self.x=self.x+y
    
    t=TestClass(5)
    t.foo(4)
    t.x         #returns 9
    
    v=TestClass(t)
    v.foo(3)
    v.x        #returns 12
    
    m=TestClass(t).foo(3)
    m.x       #Attribute Error: 'NoneType" object has no attribute 'x'
    
    Why does m.x not behave the same as v.x?
     
  2. macrumors member

    Joined:
    Aug 21, 2011
    #2
    Because you are assigning the result of TestClass(t).foo(3) to m. So, m will be the number 12 (EDIT: Not the number 12, but rather None. I don't use Python, so I assume that is like undefined, in which case you need to return something from that function if you want to use it like that). And that doesn't have an x attribute.

    Compare to the other cases, where you assign just TestClass(t) and then as a separate line call foo.
     
  3. thread starter macrumors 68030

    Analog Kid

    Joined:
    Mar 4, 2003
    #3
    Doh! Of course...

    Thanks!
     

Share This Page