I have the following code.
class SomeClass:
a = lambda self: self.b()
def __init__(self):
self.b = lambda self: None
s = SomeClass()
s.a()
It give me "TypeError: () takes exactly 1 argument (0 given)". And I want to understand why.
My explanation:
a - class method, so
s.a()equlasSomeClass.a(s)b - object's attribute (not a method, just a function), that is why
self.b()doesn't equalSomeClass.b(self)So in
a = lambda self: self.b()argument forbis missing.Am I right?
P.S. Is it closure effect?
class SomeClass: a = lambda self: self.b() def __init__(self): self.data = 12 self.b = lambda: self.data s = SomeClass() print s.a() #12 s.data = 24 print s.a() #24
a = lambda self: self.b(self)? -- although that seems atrociously unreadable (and maybe not correct). Why uselambdain a class definition like that?selfforais implicitly bound like normal, becauseais a method defined on the class (doesn't matter if you uselambdaordef, it's still a method, thoughdefis preferred for other reasons, e.g. the method knows its own name). It doesn't happen forb, becausebis a function that just happens to be an attribute of the instance, not a method (methods are defined at class definition level, not in instance initializer, you'd need metaprogramming nonsense to make them actual bound methods in the initializer; don't do it).