i am learning classes in python and i found some functions called magic methods or special methods that we use them inside the class definitions , the question is the following :
if we add double underlines before and after any original built in function , does that allow us to use all them inside a class to do the same task , for example .
>>> int (3.6)
3
>>> str(3.7)
'3.7'
and we can use str in class as following :
class Character:
def __init__(self, name, initial_health):
self.name = name
self.health = initial_health
self.inventory = []
def __str__(self):
s = "Name: " + self.name
s += " Health: " + str(self.health)
s += " Inventory: " + str(self.inventory)
return s
def grab(self, item):
self.inventory.append(item)
def get_health(self):
return self.health
def example():
me = Character("Bob", 20)
print str(me)
me.grab("pencil")
me.grab("paper")
print str(me)
print "Health:", me.get_health()
example()
the result :
Name: Bob Health: 20 Inventory: []
Name: Bob Health: 20 Inventory: ['pencil', 'paper']
Health: 20
is all built in functions can be magic (special) functions ?
thanks.
No. Some built-in functions have a special method for them, some don’t. Also some special methods don’t correspond to a built-in function, and some built-in functions make use of a special method with a different name (e.g.,
__instancecheck__). You can see which special methods there are in the documentation. This is also a good reference site.