简体   繁体   中英

Python: Parent Class not recognizing __init__ of its subclasses

I have been working with inheritance, but I got confused as to why my parent class is not recognizing the init of my sub classes. Here is an example of my code that is giving me none when run, when it shouldn't.

class Coins(object):
    def make_change(self, amount):
        change = []
        for coin in (self._coins):
            change.append(amount // coin)
            amount = amount - change[-1] * coin 
class US_Coins(Coins):
    def __init__(self):
        self._coins = [50, 25, 10, 5, 1]
class Metric_Coins(Coins):
    def __init__(self):
        self._coins = [50, 20, 10, 5, 2, 1]
metric = Metric_Coins()
us = US_Coins()
print(us.make_change(73))
print(metric.make_change(73))
coins = Coins()
print(coins.make_change(27))

You need to define self._coins field in Coins class. Without it, function make_change cannot be executed because it evokes field that does not exist in this parent class ( for coin in (self._coins) ).

Edited: in order to achieve your goal you need to create a field inside Coins class:

class Coins(object):

    def __init__self():
        self._coins = []

    def make_change(self, amount):
        change = []
        for coin in (self._coins):
            change.append(amount // coin)
            amount = amount - change[-1] * coin 


class US_Coins(Coins):

    def __init__(self):
        self._coins = [50, 25, 10, 5, 1]


class Metric_Coins(Coins):

    def __init__(self):
        self._coins = [50, 20, 10, 5, 2, 1]


metric = Metric_Coins()
us = US_Coins()
print(us.make_change(73))
print(metric.make_change(73))
coins = Coins()
print(coins.make_change(27))

Now you are able to operate with make_change method on the us and metric; and also on coins object.

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