Python:Understanding inheritance
Question: Am new to Python and was exploring Classes and Object. I have created a
class,defined few function in it. Then I have created another class and was
trying to inherit from the first class but got some error. **Error:** class
CTC(Salary): NameError: name 'Salary' is not defined

**Base Class:**

    
    
    class Salary:
    
        monthly=0.00
        name = ""
    
        def __init__(self,name,monthly):
            self.name = name
            self.monthly = monthly
    
    
        def display(self):
            print("name: ", self.name,  "Monthly Salary: ", self.monthly)
    

**Derived Class:**

    
    
    class CTC(Salary):
    
        tax=0.00
        ctc=0.00
        def __init__(self,name,monthly,tax):
            Salary.__init__(self,name,monthly)
            self.tax = tax
    
    
        def calculateCTC(self):
             yearly = monthly*12
             totalTax= tax *12
             ctc = yearly - totalTax
             print("Total CTC: ", self.ctc)
    
             obj = CTC("Rishi",28700.00,1295.00)
             obj.display(self)
    

Can anyone explain me the root cause for the error?


Answer: I put all code in one file (with minor modifiactions) and it works form me.

    
    
    class Salary:
    
        def __init__(self, name, monthly):
            self.name = name
            self.monthly = monthly
    
        def display(self):
            print("name: ", self.name,  "Monthly Salary: ", self.monthly)
    
    
    class CTC(Salary):
    
        def __init__(self, name, monthly, tax):
            Salary.__init__(self, name, monthly)
            self.tax = tax
            self.ctc = 0.00 # create with default value
    
        def calculateCTC(self):
            yearly = self.monthly*12 # with `self`
            totalTax = self.tax*12 # with `self`
            self.ctc = yearly - totalTax # with `self`
            print("Total CTC: ", self.ctc)
    
    # without indentation
    obj = CTC("Rishi", 28700.00, 1295.00)
    obj.display() # without `self`
    

if you need it in separated files

salary.py

    
    
    class Salary:
    
        def __init__(self, name, monthly):
            self.name = name
            self.monthly = monthly
    
        def display(self):
            print("name: ", self.name,  "Monthly Salary: ", self.monthly)
    

main.py

    
    
    from salary import Salary
    
    class CTC(Salary):
    
        def __init__(self, name, monthly, tax):
            Salary.__init__(self, name, monthly)
            self.tax = tax
            self.ctc = 0.00
    
        def calculateCTC(self):
            yearly = self.monthly*12 # with `self`
            totalTax = self.tax*12 # with `self`
            self.ctc = yearly - totalTax # with `self`
            print("Total CTC: ", self.ctc)
    
    # without indentation
    obj = CTC("Rishi", 28700.00, 1295.00)
    obj.display() # without `self`
    

