Being probably one of the worst OOP programmers on the planet, I’ve been reading through a lot of example code to help ‘get’ what a class can be used for. Recently I found this example:
class NextClass: # define class
def printer(self, text): # define method
self.message = text # change instance
print self.message # access instance
x = NextClass() # make instance
x.printer('instance call') # call its method
print x.message # instance changed
NextClass.printer(x, 'class call') # direct class call
print x.message # instance changed again
It doesn’t appear there is any difference between what the direct class call does and the instance call does; but it goes against the Zen to include features like that without some use to them. So if there is a difference, what is it? Performance? Overhead reduction? Maybe readability?
There is no difference.
instance.method(...)isclass.method(instance, ...). But this doesn’t go against the Zen, since it says (emphasis mine):The second way is possible, and everyone with good knowledge of Python should know that (and why), but it’s a nonobvious way of doing that, nobody does it in real code.
So why is it that way? It’s just how methods work in any language – a method is some code that operates on an object/instance (and possibly more arguments). Except that usually, the instance is supplied implicitly (e.g.
thisin C++/Java/D) – but since the Zen says “explicit is better than implicit”, self is explicitly a parameter of every method, which inevitable allows this. Explicitly prohibiting it would be pointless.And apart from that, the fact that methods are not forced to (implicitly) take an instance allows class methods and static methods to be defined without special treatment of the language – the first is just a method that expects a class instead of an instance, and the latter is just a method that doesn’t expect an instance at all.