简体   繁体   中英

Python Inheritance - Carrying a user inputted value from parent to child class

class Tax():

    def __init__(self,user_pre_tax, after_federal_tax_amount):
        self.user_pre_tax = user_pre_tax
        self.after_federal_tax_amount = after_federal_tax_amount
    def basic_information():
        federal_tax_rate = 0.10
        user_name = (input("Enter name: "))
        user_pre_tax = (int(input("Enter pre tax amount: ")))
        federal_tax_amount = user_pre_tax * federal_tax_rate
        after_federal_tax_amount = user_pre_tax - federal_tax_amount
        print ("Federal Tax Amount: ", federal_tax_amount)

class OregonTax(Tax):
    def __init__(self,user_pre_tax, after_federal_tax_amount):
        super().__init__(user_pre_tax, after_federal_tax_amount)
    def OregonTax():
        oregon_tax_rate = 0.03
        oregon_tax_amount = Tax.user_pre_tax * oregon_tax_rate
        after_oregon_tax_amount = Tax.after_federal_tax_amount - oregon_tax_amount
        print ("Oregon Tax Amount: ", oregon_tax_amount)

class WashingtonTax(Tax):
    def __init__(self,user_pre_tax, after_federal_tax_amount):
        super().__init__(user_pre_tax, after_federal_tax_amount)
    def OregonTax():
        wa_tax_rate = 0.04
        wa_tax_amount = Tax.user_pre_tax * wa_tax_rate
        after_oregon_tax_amount = Tax.after_federal_tax_amount - wa_tax_amount
        print ("Oregon Tax Amount: ", wa_tax_amount)


example1 = OregonTax
OregonTax.basic_information()
OregonTax.OregonTax()

I am trying to carrying the "after_federal_tax_amount" from the parent to child class. Since it is a user inputted value, I don't think I can place it in the the init. Otherwise, when I initialize the class at the end, I would need to enter a value as its parameter.

I was wondering how I could by pass this problem.

First of all, there is a numerous problems with your classes structure. in the function OregonTax you are trying to access Tax.user_pre_tax and Tax.after_federal_tax_amount , whilst both of them are actually do not exist for an abstract class, but exists per instance only, if you want to be able to access them like that you would need to assign those values outside the init function per class instance. But I don't really see a purpose of that, since you already create such attributes for both Oregon and Washington classes and if you pass self to the OregonTax function, you would be able to access it by calling self.after_federal_tax_amount and there is no particular need to access parent class in any way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM