Adding methods to Python classes
The normal way to add functionality (methods) to a class in Python is to define functions in the class body. There are many other ways to accomplish this that can be useful in different situations.
This is the traditional way
1.
class
A(object):
2.
def
print_classname(
self
):
3.
print
self
.__class__.__name__
The method can also be defined outside the scope of the class. This allows the function “print_classname” to be used as a standalone function and as a method of the class.
1.
def
print_classname(a):
2.
print
a.__class__.__name__
3.
4.
class
A(object):
5.
print_classname
=
print_classname
Or, equivalently
1.
def
print_classname(a):
2.
print
a.__class__.__name__
3.
4.
class
A(object):
5.
pass
6.
7.
setattr(A,
"print_classname"
, print_classname)
Adding the method to an object of type “A” is also possible. However, you need to specify that the attribute “print_classname” of the object is a method to make sure it will receive a reference to “self” as implicit first parameter when it is called.
01.
from
types
import
MethodType
02.
03.
def
print_classname(a):
04.
print
a.__class__.__name__
05.
06.
class
A(object):
07.
pass
08.
09.
# this assigns the method to the instance a, but not to the class definition
10.
a
=
A()
11.
a.print_classname
=
MethodType(print_classname, a, A)
12.
13.
# this assigns the method to the class definition
14.
A.print_classname
=
MethodType(print_classname,
None
, A)
Specific methods from another class can also be added (without inherit everything else) by adding the underlying function of the method. Otherwise the method will expect a reference to an instance of the original class as implicit first parameter.
01.
class
B(object):
02.
def
print_classname(
self
):
03.
print
self
.__class__.__name__
04.
05.
# option 1
06.
class
A(object):
07.
print_classname
=
B.print_classname.__func__
08.
09.
# option 2
10.
class
A(object):
11.
pass
12.
13.
setattr(A,
"print_classname"
, B.print_classname.__func__)
Great writeup. Is there a way to add a method to a different class in Python 3? __func__ is gone
not sure, but i think you can’t as the concept of an *unbound* method has disappeared in Python 3 (see: https://stackoverflow.com/questions/3589311/get-defining-class-of-unbound-method-object-in-python-3/25959545#25959545)…
nice to hear this. you have the great site!