Как инициализировать унаследованный класс в Python - PullRequest
1 голос
/ 16 июня 2020

Мне трудно понять, как инициализировать унаследованный класс в python OOP.

Я не могу понять, какие аргументы нужно передать, когда я его инициализирую. Это классы, которые я использую:

class BankAccount:  #parent class

    def __init__(self, owner, balance):
        self.owner = owner
        self.balance = balance

    def withdrawal(self, withdraw):
        if withdraw > self.balance:
            raise RuntimeError('Sorry, Insufficient Funds!')
        else:
            print('Withdrawal accepted.')
            self.balance -= withdraw
            show_balance = input('See account balance? enter y or n: ')
            if show_balance == 'y':
                print(self.balance)

    def deposit(self, amt):
        self.balance += amt
        print('Deposit Accepted')
        show_balance = input('See account balance? enter y or n: ')
        if show_balance == 'y':
            print(self.balance)


class MinimumBalanceAccount(BankAccount):        #child class

    minimum_balance = 100

    def __init__(self):
        BankAccount.__init__(self)

    def withdrawal(self, withdraw):
        if self.balance - withdraw < self.minimum_balance:
            print('Error, balance cannot go below minimum value: {}'.format(minimum_balance))
        else:
            self.balance -= withdraw

Но когда я пытаюсь инициализировать дочерний класс:

acc2 = MinimumBalanceAccount('Milind', 1000)    # I am not sure what to pass as arguments here

Python дает мне эту ошибку:

TypeError                                 Traceback (most recent call last)
<ipython-input-9-85e55fb15340> in <module>
----> 1 acc2 = MinimumBalanceAccount('milind', 1000)

TypeError: __init__() takes 1 positional argument but 3 were given

Что я передаю в качестве аргументов ?? Что не так?

Ответы [ 3 ]

2 голосов
/ 16 июня 2020

Вам необходимо передать обязательные аргументы подклассу и суперклассу:

class BankAccount:

    def __init__(self, owner, balance):
        self.owner = owner
        self.balance = balance

    def withdrawal(self, withdraw):
        if withdraw > self.balance:
            raise RuntimeError('Sorry, Insufficient Funds!')
        else:
            print('Withdrawal accepted.')
            self.balance -= withdraw
            show_balance = input('See account balance? enter y or n: ')
            if show_balance == 'y':
                print(self.balance)

    def deposit(self, amt):
        self.balance += amt
        print('Deposit Accepted')
        show_balance = input('See account balance? enter y or n: ')
        if show_balance == 'y':
            print(self.balance)


class MinimumBalanceAccount(BankAccount):

    minimum_balance = 100

    def __init__(self, owner, balance):
        super().__init__(owner, balance)
        self.minimum_balance = MinimumBalanceAccount.minimum_balance

    def withdrawal(self, withdraw):
        if self.balance - withdraw < self.minimum_balance:
            print('Error, balance cannot go below minimum value: {}'.format(minimum_balance))
        else:
            self.balance -= withdraw

acc2 = MinimumBalanceAccount('Milind', 1000)

В этом случае, как указано @Deceze в комментариях, вы можете полностью опустить __init__:

class MinimumBalanceAccount(BankAccount):        #child class

    minimum_balance = 100

    def withdrawal(self, withdraw):
        if self.balance - withdraw < self.minimum_balance:
            print('Error, balance cannot go below minimum value: {}'.format(minimum_balance))
        else:
            self.balance -= withdraw
1 голос
/ 16 июня 2020

Вам необходимо добавить параметры инициализации также в ваш дочерний класс, когда вы определяете функцию __init__ и передаете ее родительскому классу.

class MinimumBalanceAccount(BankAccount):        #child class

    minimum_balance = 100

    def __init__(self, owner, balance):
        BankAccount.__init__(self, owner, balance)
0 голосов
/ 16 июня 2020

класс MinimumBalanceAccount (BankAccount): #child class

minimum_balance = 100

def __init__(self,owner, balance):
    BankAccount.__init__(self,owner,balance)

def withdrawal(self, withdraw):
    if self.balance - withdraw < self.minimum_balance:
        print('Error, balance cannot go below minimum value: {}'.format(minimum_balance))
    else:
        self.balance -= withdraw
...