Python methods are usually defined by writing a def
statement in the class definition as follows: (All code is Python3.)
python
class Foo:
def __init__(self, name):
self.name = name
def print_name(self):
print(self.name)
#Create an instance of Foo
foo = Foo('foo')
However, you can also define a normal function by writing it outside the class after defining the class and setting the function to the attributes of the class. In this way, if the above print_name
method is defined outside the class:
python
class Bar:
def __init__(self, name):
self.name = name
#Create an instance of Bar
bar = Bar('bar')
def print_name(self):
print(self.name)
Bar.print_name = print_name
Comparing the behavior and type of print_name
of foo
and bar
, the output is as follows.
python
>>> foo.print_name()
foo
>>> bar.print_name()
bar
>>> foo.print_name
<bound method Foo.print_name of <__main__.Foo object at 0x03C83610>>
>>> bar.print_name
<bound method Bar.print_name of <__main__.Bar object at 0x042F5D10>>
In both foo
and bar
, the type of print_name
is bound method
, and you can see that even if you define it with a function, you can define the method in exactly the same way as you define it in the class definition.
Recommended Posts