0

I tried to inherit a method and use it to access a variable defined in my subclass. Here's a very simple example of what I mean:

class A(object):
    def __init__(self):
        self.__type='parent'
    def type(self):
        return self.__type

class B(A):
    def __init__(self):
        super(B,self).__init__()
        self.__type='child'

x=B()
print x.type()

Python returns 'parent' as the result. I assume this is something to do with the method type being defined within the scope of class A and can only access things defined in class A.

What's considered the most elegant way to avoid defining my method in my sub class?

  • There is no property here. You do have an *attribute*, one with double underscores which means Python will *mangle the name*. You have `_A__type` in the first class and `_B__type` in the second, so the code you have sets two different attributes. – Martijn Pieters Sep 17 '16 at 14:15
  • 1
    Double-underscore attribute names are meant to *avoid clashes with subclasses*. Don't use double-underscore names if you explicitly *do* want the subclass to be able to override the name. Use `self._type` here. See the duplicate as to what the difference is. – Martijn Pieters Sep 17 '16 at 14:16
  • @MartijnPieters This might be answered by another question, but Python's double underscore mangling convention is not obvious, and I would argue that a programmer from another language would find the answer to a similar problem a lot easier from this question than from maybe stumbling across the other question. Could you please consider un-duplicating this and adding the fixed code as the answer, linking to the answer with the mangling convention? Or unduplicating the question, and I'll post the code I have. – Ben Sep 17 '16 at 14:21
  • @Ben: I already gave the solution in my comment; just rename `__type` to `_type`. There is a misunderstanding that `__name` is the same as 'private' in languages like Java or C#, so it is *important* that the documentation is read about what this really does, which is what the other post shows. – Martijn Pieters Sep 17 '16 at 14:25
  • @Ben: so no, I'm not considering unduplicating this. – Martijn Pieters Sep 17 '16 at 14:25

0 Answers0