Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

Analog Kid

macrumors G3
Original poster
Mar 4, 2003
8,869
11,410
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?
 

dylanryan

macrumors member
Aug 21, 2011
57
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.
 

Analog Kid

macrumors G3
Original poster
Mar 4, 2003
8,869
11,410
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.

Doh! Of course...

Thanks!
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.