Skip to main content

Inheritance and Built-in function decorators (Class method and Static method)

 https://stackoverflow.com/a/34885285






# multi level inheritance

class GrandFather:

    def __init__(self, grandfathername):

        self.grandfathername = grandfathername


class Father(GrandFather):

    def __init__(self, fathername, grandfathername):

        self.fathername = fathername

        super(Father, self).__init__(grandfathername)


class Son(Father):

    def __init__(self, sonname, fathername, grandfathername):

        self.sonname = sonname

        super(Son, self).__init__(fathername, grandfathername)

        

s = Son('SonName', 'FatherName', 'GrandfatherName')

print(s.sonname, s.fathername, s.grandfathername)


# multiple inheritance

class Dad():

    def __init__(self, dadname, **kw):

        self.dadname = dadname

        super(Dad, self).__init__(**kw) #important


class Mom():

    def __init__(self, momname, **kw):

        self.momname = momname

        super(Mom, self).__init__(**kw) #important


class Baby(Dad, Mom):

    def __init__(self, babyname, dadname, momname):

        self.babyname = babyname

        super(Baby, self).__init__(dadname=dadname, momname=momname)


b = Baby('BabyName', 'DadName', 'MomName')

print(b.babyname, b.dadname, b.momname)



class Fruit:

    

    def __init__(self, fruitname):

        self.fruitname = fruitname

    

    def get_fruitname(self):

        return self.fruitname

    

    @classmethod #kind of like function overloading, i.e. constructor overloading in this case

    def set_fruitname_with_weight(cls, fruitname, weight):

        return cls(fruitname + '_' + str(weight))

    

    @staticmethod

    def get_applename():

        return 'apple'


a = Fruit('greenapple')

print(Fruit.get_applename())

print(a.get_applename())

print(a.get_fruitname())

b = Fruit('banana').set_fruitname_with_weight('banana', 33)

print(b.get_fruitname())