How to avoid explicit ‘self’ in Python?

Python requires specifying self. The result is there’s never any confusion over what’s a member and what’s not, even without the full class definition visible. This leads to useful properties, such as: you can’t add members which accidentally shadow non-members and thereby break code. One extreme example: you can write a class without any knowledge … Read more

Python decorators in classes

Would something like this do what you need? class Test(object): def _decorator(foo): def magic( self ) : print “start magic” foo( self ) print “end magic” return magic @_decorator def bar( self ) : print “normal call” test = Test() test.bar() This avoids the call to self to access the decorator and leaves it hidden … Read more

TypeError: method() takes 1 positional argument but 2 were given

In Python, this: my_object.method(“foo”) …is syntactic sugar, which the interpreter translates behind the scenes into: MyClass.method(my_object, “foo”) …which, as you can see, does indeed have two arguments – it’s just that the first one is implicit, from the point of view of the caller. This is because most methods do some work with the object … Read more

What do __init__ and self do in Python?

In this code: class A(object): def __init__(self): self.x = ‘Hello’ def method_a(self, foo): print self.x + ‘ ‘ + foo … the self variable represents the instance of the object itself. Most object-oriented languages pass this as a hidden parameter to the methods defined on an object; Python does not. You have to declare it … Read more