Special Method, which is also called Magic Method, is a kind of method that can be set in user-defined class objects. It is usually surrounded by two Under-bars at head and tail of the keyword like __init__
, __str__
, etc.
With Spcial Method, your script must be more pythonic and more efficient.
You can
Take a look at the below code. At the bottom, I commanded to print()
the parameter with the identifiter japan
. At this, the japan
is the instance of the class which I defined. So, the code prints the infomation of the type about the japan
.
class country:
def __init__(self, name, population):
self.name = name
self.population = population
japan = country('Japan', '125m')
print(japan)
# <__main__.country object at 0x7f0d90322290>
As Known, this is the expected output. However, there will be something different with Special Method.
class country:
def __init__(self, name, population):
self.name = name
self.population = population
# Add Specical Method inside the class
def __str__(self):
return f'name : {self.name}, population : {self.population}'
japan = country('Japan', '125m')
print(japan)
# name : Japan, population : 125m
At the bottom, I also commanded to print()
the parameter with the identifiter japan
. And then, the code prints the string from return
of instance method '__str__()
' inside the class japan
.
Therefore, you can get string from class, just as parameter.
class country:
def __init__(self, name, population):
self.name = name
self.population = population
japan = country('Japan', '125m')
japan()
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-3-88c499f4f664> in <module>()
6 japan = country('Japan', '125m')
7
----> 8 japan()
TypeError: 'country' object is not callable
class country:
def __init__(self, name, population):
self.name = name
self.population = population
def __call__(self):
print(f'name : {self.name}, population : {self.population}')
japan = country('Japan', '125m')
japan()
name : Japan, population : 125m