2

I am attempting to build a framework for parsing a very specific text structure. The structure that I am processing is rich and has a known schema, similar to xml. I am attempting to build an framework to do the parsing. The text has various sections and I anticipate that more sections code be added in the future. To Compensate, I am attempting to build a series of derived classed that can be swapped in or out as needed.

I thought everything was going as planned, until I started coding up the first derived class. The base class has some functionality inside of __init__ that I was expecting that I would get for free in all of the concrete derived classes. That however, doesn't seem to be the case at all.

Here is a simple example to illustrate my problem: I would expect the output to be:

['memberA', 'memberB', 'memberC'], ['DerivedA', 'DerivedB', 'DerivedC']

class base(object):
    def __init__(self):
        members = [attr for attr in dir(self) if not callable(attr) and not attr.startswith("__")]
        print members

class test(base):
    def __init__(self):
        self.memberA = None
        self.memberB = None
        self.memberC = None


class test2(test):
    def __init__(self):
        self.DerivedA = None
        self.DerivedB = None
        self.DerivedC = None

t = test()
t2 = test2()

Can someone please explain to my, why the print functionality is not working as I expect it?

EDIT: in light of the answer below: I now have this question:

What if base.__init(self) instead looked like:

class base(object):
    def __init__(self, text):

would I have to define the derived class as:

class test(base):
    def __init__(self, text):
        base.__init__(self, text)

I was hoping to at least get the parameter object referance for free

2 Answers 2

7

In Python, you must call the base class's __init__ explicitly inside test.__init__:

class test(base):
    def __init__(self):
        base.__init__(self)

Or, if you wish to support multiple inheritance, use super:

class test(base):
    def __init__(self):
        super(test, self).__init__()

If the base.__init__ looks like

class base(object):
    def __init__(self, text):

then test.__init__ should indeed look like

class test(base):
    def __init__(self, text):
        base.__init__(self, text)

See Guido van Rossum's blog for why self is explicit in Python.


PS. PEP8 recommends using CapWords for class names.

Sign up to request clarification or add additional context in comments.

Comments

0

you are overwriting init in test2

following code will complete overwrite init in test. so there is no longer a print int the init function.

def __init__(self):
    self.DerivedA = None
    self.DerivedB = None
    self.DerivedC = None

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.