What is the difference between the following class methods?
Is it that one is static and the other is not?
class Test(object):
def method_one(self):
print "Called method_one"
def method_two():
print "Called method_two"
a_test = Test()
a_test.method_one()
a_test.method_two()
When you call a class member, Python automatically uses a reference to the object as the first parameter. The variable
self
actually means nothing, it's just a coding convention. You could call itgargaloo
if you wanted. That said, the call tomethod_two
would raise aTypeError
, because Python is automatically trying to pass a parameter (the reference to its parent object) to a method that was defined as having no parameters.To actually make it work, you could append this to your class definition:
or you could use the
@staticmethod
function decorator.In Python, there is a distinction between bound and unbound methods.
Basically, a call to a member function (like
method_one
), a bound functionis translated to
i.e. a call to an unbound method. Because of that, a call to your version of
method_two
will fail with aTypeError
You can change the behavior of a method using a decorator
The decorator tells the built-in default metaclass
type
(the class of a class, cf. this question) to not create bound methods formethod_two
.Now, you can invoke static method both on an instance or on the class directly:
The second one won't work because when you call it like that python internally tries to call it with the a_test instance as the first argument, but your method_two doesn't accept any arguments, so it wont work, you'll get a runtime error. If you want the equivalent of a static method you can use a class method. There's much less need for class methods in Python than static methods in languages like Java or C#. Most often the best solution is to use a method in the module, outside a class definition, those work more efficiently than class methods.