Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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 !

share|improve this question
    
That is perfectly normal behaviour. –  Martijn Pieters Feb 28 '13 at 16:28

1 Answer 1

up vote 3 down vote accepted

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.

share|improve this answer
    
You are absolutely right ! Thank you for the help! –  user2120336 Feb 28 '13 at 16:31
    
Now I need to figure how to ask the owner of the Father class to change his code. Because I am writing the Child class ... hmm ... –  user2120336 Feb 28 '13 at 16:33

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.