-2

I have a subclass cal which inherits from read, but when I create an instance, I cannot access the parent attributes from the child's methods:

class read:
  def __init__(self,p,t,r):
    self.p = p
    self.t = t
    self.r = r
    
  def dis(self):
    print('Principle amount:',self.p)
    print('No.Of.Years:',self.t)
    print('Rate of interest:',self.r)
    

class cal(read):
  def calu(self):
    print('Simple Interest:'(self.p*self.t*self.r)/100)
  
a = int(input())
b = int(input())
c = int(input())
ob = read(a,b,c)
ob.dis()
obj = cal()
obj.calu()

This code produces an error when executing obj = cal(). I have tried to find the cause, but I can't understand where I made mistake.

trincot
  • 317,000
  • 35
  • 244
  • 286

1 Answers1

0

As you use inheritance, subclassing read into cal, and you expect to use a method that is defined only for a cal instance, you should instantiate a cal object, not a read object.

So the last few lines of your code should be:

ob = cal(a,b,c)
ob.dis()
ob.calu()

Other remarks

A comma is missing in your last print call:

print('Simple Interest:', (self.p*self.t*self.r)/100)
#                       ^^

Please use more descriptive names. One-lettered names are really not that helpful for anyone to understand your code.

Look how the readability improves when you just use full words:

class Loan:
  def __init__(self, principle, numyears, interestrate):
    self.principle = principle
    self.numyears = numyears
    self.interestrate = interestrate
    
  def display(self):
    print('Principle amount:', self.principle)
    print('Number of years:', self.numyears)
    print('Rate of interest:', self.interestrate)
    
class LoanCalculator(Loan):
  def display_simpleinterest(self):
    print('Simple Interest:',
         (self.principle * self.numyears * self.interestrate) / 100
    )
  
principle = int(input("Principle amount? "))
numyears = int(input("Number of years? "))
interestrate = int(input("Rate of interest? "))
ob = LoanCalculator(principle, numyears, interestrate)
ob.display()
ob.display_simpleinterest()

As a further improvement, I would not have methods that print. Leave printing to the code that uses your class. Instead, you could define methods that return a calculated value, or a formatted string. That way the caller can decide what to do with that return value: print it, write it to a file, collect it in some other data structure, ...etc, making your classes more flexible to use.

trincot
  • 317,000
  • 35
  • 244
  • 286