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?

1
  • Can you give us the broader context of what you're trying to do? It looks like you're on the wrong track. Commented May 20, 2018 at 16:01

1 Answer 1

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.')
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.