I am learning python classes and could not understand below behavior:
In below example, I am extending built-in str
class:
class uStr(str):
def __init__(self,u_str):
str.__init__(u_str) #<<<------- no self is needed
def underline(self):
underlines = format('', '-^' + str(len(self)))
return str.__str__(self) + '\n' + underlines
In below example, I am extending a user-defined class Fraction
:
from fraction import *
class MixedFraction(Fraction):
def __init__(self, *args):
Fraction.__init__(self, args[0], args[1]) #<<<-------self is needed
def getWholeNum(self):
return self.getNumerator() // self.getDenominator()
Why do we need to give self
as argument in 2nd example in calling __init__
of super class, while there is no need to give self
in calling str
's __init__
.