Instance method, class method, and static method in Python
Examples of instance, class, and static methods in Python code.
class A(object):
def func(self, x):
print("Executing func(%s, %s)." % (self, x))
@classmethod
def class_func(cls, x):
print("Executing class_func(%s, %s)." % (cls, x))
@staticmethod
def static_func(x):
print("Executing static_func(%s)." % x)
def func2(x):
print("Executing func2(%s)." % x)
def func3():
print("Executing func3.")a = A()
Regular instance method
func(self, x)
is a regular object method.
a.func(1)Executing func(<__main__.A object at 0x7f862482b748>, 1).
When func
is called by the class A
, self
(the object instance) is not passed to func
, causing an error.
A.func(1)---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-12-e93655bce7f5> in <module>()
----> 1 A.func(1)TypeError: func() missing 1 required positional argument: 'x'
This fabricated case allows A
to call func
in unintened way.
A.func(1, 1)Executing func(1, 1).
classmethod
class_func(cls, x)
is a @classmethod
. The class is passed to func as the first argument.
a.class_func(1)Executing class_func(<class '__main__.A'>, 1).A.class_func(1)Executing class_func(<class '__main__.A'>, 1).
staticmethod
static_func(x)
is a @staticmethod
. It can be called by the object and the class without passing the object instance or the class.
a.static_func(1)Executing static_func(1).A.static_func(1)Executing static_func(1).
An odd case
func2(x)
is the same as func2(self)
expect using an unconventional name x
instead of self
.
a.func2(1)---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-21-0645ed4a8d11> in <module>()
----> 1 a.func2(1)TypeError: func2() takes 1 positional argument but 2 were givena.func2()Executing func2(<__main__.A object at 0x7f862482b748>).
This fabricated case allows A
to call func2
in unintened way.
A.func2(1)Executing func2(1).
Another odd case
func3()
fails to define argument self
therefore cannot be called by a
because a
will pass it the object instance (i.e., a
itself
).
a.func3()---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-138-4b5d5e1ac25c> in <module>()
----> 1 a.foo3()TypeError: foo3() takes 0 positional arguments but 1 was given
This fabricated case allows A
to call func3
in unintened way.
A.func3()Executing func3.
References:
- Java for Python Programmers
- https://stackoverflow.com/questions/136097/what-is-the-difference-between-staticmethod-and-classmethod-in-python
Code is here: https://github.com/yang-zhang/yang-zhang.github.io/blob/master/coding/method_types_python.ipynb