PDA

View Full Version : Python constructor syntax




Analog Kid
Feb 22, 2012, 10:44 PM
Can someone explain why this is behaving how it is:


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
Feb 22, 2012, 11:17 PM
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
Feb 22, 2012, 11:56 PM
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!