2

I need something like this

class Parent(object): 
    class Base(object):
        def __init__(self, a, b):
            self.a = a
            self.b = b


    class Derived(Base):
        def __init__(self, a, b, c):
            super(Derived,self).__init__(a, b)
            self.c = c

        def doit():
            pass

parent = Parent()
derived = parent.Derived(x,y,z)
derived.doit()

When I try to run this, i get this following error: NameError: name 'Derived' is not defined

I tried with 'Base' in the place of 'Derived' in super() - didn't help

6
  • 1
    Why would you want to do this? What's the point of that nesting? Commented Apr 17, 2015 at 13:43
  • 1
    Would it not just be better to declare Derived inside of Parent? Commented Apr 17, 2015 at 13:46
  • what python version are you running? is it not enough to go with super().__init__ ? Commented Apr 17, 2015 at 13:48
  • You are trying to call Derived inside the Parent class, wich doesn't exist, and you get the NameError. What are you trying to achieve? Commented Apr 17, 2015 at 13:49
  • @daniel: the 'Derived' object should not exist without a 'Parent' object. A remotely similar example is 'Note' written in a paper, cannot exist without 'Paper' object. Commented Apr 19, 2015 at 16:17

2 Answers 2

2

Class inheritance does not change the parent class. In this case your Parent class only contains the original Base class and not the derived class.

You can simply use monkey-patching to solve this problem,

class Parent(object): 
    pass


class Base(object):
    def __init__(self, a, b):
        self.a = a
        self.b = b


class Derived(Base):
    def __init__(self, a, b, c):
        super(Derived,self).__init__(a, b)
        self.c = c

    def doit(self):
        pass

Parent.Derived = Derived

parent = Parent()
x, y , z = 1, 1, 1
derived = parent.Derived(x,y,z)
derived.doit()
Sign up to request clarification or add additional context in comments.

Comments

0

Prefixing 'Derived' with 'Parent.', made it. As I already have commented on the question. This is just for experimenting with the 'Derived' class. But I am still wondering how the, 'class Derived(Base):' is fine (without 'Parent.' prefix for 'Base' class)

class Parent(object): 
    class Base(object):
        def __init__(self, a, b):
            self.a = a
            self.b = b


    class Derived(Base):
        def __init__(self, a, b, c):
            super(Parent.Derived,self).__init__(a, b)
            self.c = c

        def doit():
            pass

parent = Parent()
derived = parent.Derived(x,y,z)
derived.doit()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.