将构造函数参数传递给生成默认值的函数失败

时间:2016-02-06 17:21:55

标签: python-2.7

我对Python很陌生,所以我认为我做的事情非常糟糕,但我看不出是什么,谷歌也没有帮助过这一点。这有什么问题?

ProductEntry

调用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 的构造函数失败:

public interface ITargetableUnit {
        //Returns whether the object of a class that implements this interface is targetable
     bool unitCanBeTargeted(){
        bool targetable = false;
        if(this is Insect){
            targetable = (this as Insect).isFasterThanLight();
        }
        else if(this is FighterJet){
            targetable = !(this as FighterJet).Flying;
        }
        else if(this is Zombie){
            targetable = !(this as Zombie).Invisible;
        }
        return targetable;
    }
}

1 个答案:

答案 0 :(得分:1)

定义函数时定义默认参数的表达式,而不是在调用函数时。在定义__init__时,name不存在,因此不能在表达式中使用它来计算默认参数。

执行此类操作的常用方法是将替换值作为默认参数,并将其替换为函数体内实际需要的值。

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)
     ...