1


Does someone know, how can I use an Enum as class constructor parameter? I have created such class:

class Coin(Cash, Enum):
    onePenny = 1
    twoPens = 2
    fivePens = 5

    ones = 0
    twos = 0
    fives = 0

    def __init__(self, val):
        if val == onePenny:
            Cash.value = onePenny.value
            Coin.ones += 1
        elif val == twoPens:
            Cash.value = twoPens.value
            Coin.twos += 1
        else:
            print('Not existing coin.')

When I'm trying to create an object, I get the NameError:

NameError: name 'onePenny' is not defined

How to fix it?

Druta Ruslan
  • 7,171
  • 2
  • 28
  • 38
wkondrat
  • 11
  • 1
  • 2
  • Can you give us the broader context of what you're trying to do? It looks like you're on the wrong track. – Alex Hall May 20 '18 at 16:01

1 Answers1

0

The class statement doesn't define a new scope, so you need to refer to it as you would outside the statement, as you did with ones and twos.

def __init__(self, val):
    if (val == Coin.onePenny):
        Cash.value = Coin.onePenny.value
        Coin.ones += 1
    elif (val == Coin.twoPens):
        Cash.value = Coin.twoPens.value
        Coin.twos += 1
    else:
        print('Not existing coin.')
chepner
  • 497,756
  • 71
  • 530
  • 681