0

I am very new to Python so I assume I am doing something terribly wrong, but I don't see what and Google has not helped this far too. What is wrong with this ?

def lookup_permille(name):
    # TODO: implement a permille lookup table
    return 0

def lookup_known_product(name):
    # TODO: implement a known product lookup table
    return 0

class ProductEntry:
    def __init__(self, source, name, price, volume, permille = lookup_permille(name), known_product_id = lookup_known_product(name), category = 0):
        self.source = source
        self.name = name
        self.price = price
        self.volume = volume
        self.permille = permille
        self.price_per_permille = self.permille / self.price;
        self.category = category
        self.known_product_id = known_product_id

Calling the constructor of ProductEntry fails with:

def __init__(self, source, name, price, volume, permille = lookup_permille(name), known_product_id = lookup_known_product(name), category = 0):
NameError: name 'name' is not defined

1 Answer 1

1

The expressions defining default arguments are evaluated when the function is defined, not when it is called. At the point when __init__ is being defined, name does not exist, so it cannot be used in an expression to calculate a default argument.

The usual way to do something like this is to have a stand-in value as your default argument, and replace it with whatever value you actually want inside the body of your function.

def __init__(self, source, name, price, volume,
             permille=None, known_product_id=None, category=0):
     if permille is None:
         permille = lookup_permille(name)
     if known_product_id is None:
         known_product_id = lookup_known_product(name)
     ...
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I guess I was expecting too much from Python :D I mean this would not work in C++ and for some reason I expected Python to be a magical "do-it-all" thingy:D

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.