简体   繁体   中英

How do I inherit information from an instance of a class into another instance?

I am trying to create a basic banking program that has a class with customer profile information that will be inherited by several other classes for types of account that the customer will be able to access (eg checking account, savings account). I want the product class to inherit all information from the customer profile class and then add a balance for that particular service.

Here is the code I have tried:

class Account:
    def __init__(self, name, cust_id, pin):
        self.name = name 
        self.cust_id = cust_id
        self.pin = pin

aidan_profile = Account('Aidan', 123456, 1234)

class CheckingAccount(Account):
    def __init__(self, name, cust_id, pin, balance):
        Account.__init__(self, cust_id, pin)
        self.balance = balance

aidan_checking_account = CheckingAccount(aidan_profile, balance = 1000)

How do I pass through the profile information to an instance of the checking account class?

Thanks!

You are trying to use inheritance which is a "is a" relationship in a situation that really calls for composition which is a "has a" relationship. In other words, a checking account "has a" customer profile associated with it.

Example:

class CustomerProfile:
    def __init__(self, name, cust_id, pin):
        self.name = name 
        self.cust_id = cust_id
        self.pin = pin

aidan_profile = CustomerProfile('Aidan', 123456, 1234)

class CheckingAccount:
    def __init__(self, profile, balance):
        self.profile = profile
        self.balance = balance

aidan_checking = CheckingAccount(aidan_profile, balance = 1000)

print(f"Customer {aidan_checking.profile.name} has a balance of {aidan_checking.balance} in checking.")

Output:

Customer Aidan has a balance of 1000 in checking.

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