user2120336
user2120336

Reputation: 13

python inheritance function override during init

Somehow the Father class can see the methods of the Child class. I presumed that only internal methods are available to Father during init

But apparently I am wrong. Here is the code:

class Father():
    def __init__(self):
        self.name=self.getName()
        print "from Father ->", self.name

    def getName(self):
        return "father"

class Child(Father):
    def __init__(self):         
        Father.__init__(self)
        self.name=self.getName()
        print "from Child ->", self.name

    def getName(self):
        return "child"

if __name__ == "__main__":
    import sys, pprint

    someone=Child()

And the output is

from Father -> child
from Child -> child

But I would like to get

from Father -> father
from Child -> child

Any thoughts how to rewrite it ? Tnx !

Upvotes: 1

Views: 260

Answers (1)

unutbu
unutbu

Reputation: 881017

This is the purpose for name-mangling: It allows you to say: "This class's attribute":

class Father():
    def __init__(self):
        self.name=self.__getName()
        print "from Father ->", self.name
    def __getName(self):
        return "father"

class Child(Father):
    def __init__(self):         
        Father.__init__(self)
        self.name=self.__getName()
        print "from Child ->", self.name

    def __getName(self):
        return "child"

if __name__ == "__main__":
    import sys, pprint

    someone=Child()

yields

from Father -> father
from Child -> child

For more information, see also this post.

Upvotes: 3

Related Questions