Using instance of subclass I cannot access attributes of parent class

c. chakrapani

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

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.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

How can I access property of subclass in an array of its parent class

Access same variable in subclass and parent class using different scope

Can a parent class create an instance of its subclass?

Instance subclass field using parent protected constructor

python subclass access to class variable of parent

How to access Parent class methods in subclass

c++: how can I get access to private private attributes in base class from the subclass

Subclass of class with synthesized readonly property cannot access instance variable in Objective-C

Does creating an instance of a subclass, create an instance of it's parent class in Java

How to assign a data attribute of a subclass to attributes of its parent class

PyYaml: cannot access nested instance attributes from within constructor class' __init__ method

How to access/read class instance attributes in octave?

How do I access outer class instance attributes from an inner class?

Python access derived class attributes in parent constructor

Autowiring a subclass but using parent class as reference

Extending classes and using class attributes in parent class

Check if subclass is instance of parent

No access on attributes of abstract class objects in subclass methods in java

How is creating an instance of a subclass extending an abstract parent class using a mix-up of both the class names error-free?

I can't use subclass specific funcitons when I add them to a vector using parent class pointers

Changing instance attributes of a parent class from a child class

Class Attributes and Instance Attributes

How do I mock class instance attributes?

How can I implement a class structure that allows to an instance of a subclass to change to an instance of another subclass of the same class

How to access parent class instance attribute from child class instance?

How to access an instance variable of a parent class in python?

Cannot return Subclass instance from Class.__new__()

Prevent access to an instance variable from subclass, without affecting base class

Access attributes defined in child class from parent class

TOP Ranking

  1. 1

    Failed to listen on localhost:8000 (reason: Cannot assign requested address)

  2. 2

    pump.io port in URL

  3. 3

    How to import an asset in swift using Bundle.main.path() in a react-native native module

  4. 4

    Loopback Error: connect ECONNREFUSED 127.0.0.1:3306 (MAMP)

  5. 5

    Compiler error CS0246 (type or namespace not found) on using Ninject in ASP.NET vNext

  6. 6

    BigQuery - concatenate ignoring NULL

  7. 7

    Spring Boot JPA PostgreSQL Web App - Internal Authentication Error

  8. 8

    ggplotly no applicable method for 'plotly_build' applied to an object of class "NULL" if statements

  9. 9

    ngClass error (Can't bind ngClass since it isn't a known property of div) in Angular 11.0.3

  10. 10

    How to remove the extra space from right in a webview?

  11. 11

    Change dd-mm-yyyy date format of dataframe date column to yyyy-mm-dd

  12. 12

    Jquery different data trapped from direct mousedown event and simulation via $(this).trigger('mousedown');

  13. 13

    maven-jaxb2-plugin cannot generate classes due to two declarations cause a collision in ObjectFactory class

  14. 14

    java.lang.NullPointerException: Cannot read the array length because "<local3>" is null

  15. 15

    How to use merge windows unallocated space into Ubuntu using GParted?

  16. 16

    flutter: dropdown item programmatically unselect problem

  17. 17

    Pandas - check if dataframe has negative value in any column

  18. 18

    Nuget add packages gives access denied errors

  19. 19

    Can't pre-populate phone number and message body in SMS link on iPhones when SMS app is not running in the background

  20. 20

    Generate random UUIDv4 with Elm

  21. 21

    Client secret not provided in request error with Keycloak

HotTag

Archive