Methods can be defined outside the class definition

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

Methods can be defined outside the class definition
Find out the location of Python class definition files.
Qiita can now be viewed on the console (shell)
List the classes that can be referenced by ObjCClass
[Django] Field names, user registration, and login methods that can be used in the User model