yufiP
yufiP

Reputation: 113

NameError when using a subclass in Python

I have two .py files, one for the main(main.py) module and the other containing a class and its subclass (sub.py). From the main file, I use the class as follows.

## (main.py)
# Import the superclass
from sub import Class1
# Import the subclass
from sub import Class2
# Assign the object (it gives an error as described below)
myVariable=Class2()

where I write the two classes in sub.py as

## (sub.py)
class Class1:
    def __init__(self, nugget=0):
        self.eigval=nugget
        self.eigvec=nugget        
        self.explained=nugget
class Class2(Class1):
    def __init__(self, nugget=0):
        super().__init__(eigval, eigvec, explained)
        self.ppc=nugget
        self.vol=nugget
        self.corr=nugget
        self.cov=nugget

The error I'm getting is

NameError: name 'eigval' is not defined

although I an inheriting the variable eigval using the super() in the subclass. Why would that be??

Upvotes: 0

Views: 557

Answers (1)

Cory Kramer
Cory Kramer

Reputation: 117856

You don't need to pass anything other than nugget to Class2

class Class2(Class1):
    def __init__(self, nugget=0):
        super().__init__(nugget)
        self.ppc=nugget
        self.vol=nugget
        self.corr=nugget
        self.cov=nugget

You are otherwise correct that super().__init__ will call the __init__ from Class1 and therefore your Class2 instance will have eigval, eigvec, and explained members.

>>> c = Class2()
>>> c.eigval
0

Upvotes: 1

Related Questions