TheCodeNovice
TheCodeNovice

Reputation: 692

Python subclass not recognizing inherited parent class

I am struggling with my code, specifically subclasses. I have a parent class that when initialized will call its subclass to be used as an attribute, in the form of a list of objects. I have seen numerous post where a person forgets to call the __init__() of the parent. My issue is different in that the parent is calling the child class and I do not want to call it.

I am getting the following error:

NameError: name 'bundle' is not defined

I am confused because it is clearly defined as the parent class. Any ideas?

class bundle(object):
"""Main object to hold graphical information"""
    def __init__(self, size,nzone):
        self.size = size
        self.rows = math.sqrt(size)
        self.cols = math.sqrt(size)
        subchans = []
        r = 1
        c = 1 
        for i in range (1,self.size):
            subchans.append(bundle.subbundle(r,c,self.rows,self.cols))
            r += 1            
            if r > self.rows :
                r = 1
                c += 1
    class subbundle(bundle):
        """ Defines geometry to represent subbundle"""
        def  __init__(self, row, col, rows,cols):

Upvotes: 1

Views: 3953

Answers (1)

Savir
Savir

Reputation: 18438

When I run your code, I got the error in the following line:

class subbundle(bundle):

That's because you are trying to inherit your subundle class from bundle. I don't know if that's what you actually want to do. Let's assume it is.

When Python tries to parse the .py file, it'll try to figure out the class hierarchy as soon as it sees class bundle. When the interpreter reaches class subbundle(bundle), it doesn't know (yet) what bundle is. Move it to the same level than your class bundle:

class bundle(object):
    def __init__(self, size,nzone):
        self.size = size
        [ . . .]

class subbundle(bundle):
    """ Defines geometry to represent subbundle"""
    def  __init__(self, row, col, rows,cols):
        [ . . . ]

You'll stop seeing your current error and will start seeing a new one: type object 'bundle' has no attribute 'subbundle' That's because it's attempting to treat bundle.subbundle as a method of the class bundle, which is not. You might wanna change the code in the bundle.__init__ to:

for i in range (1,self.size):
    subbundle_instance = subbundle(r, c, self.rows, self.cols)
    subchans.append(subbundle_instance)

PS: It's usually a good practice naming your classes with a capital letter (aka CamelCase) See https://www.python.org/dev/peps/pep-0008#class-names

Upvotes: 1

Related Questions