2016-09-09 3 views
-1

私は2つの引数を持っているPythonでの関数があります。たとえば異なる数の属性と別のロジックを持つPythonで関数を呼び出す方法は?

def get_shiff(instance): 
    total=0 
    if instance.x: 
     total+=instance.x/2 
    elif instance.y: 
     total.+=instance.y*40 
    return total 

が、私はこのよう別のファイルにpythonでこの関数を呼び出すことができます。

def get_shiff(instance,type) 
    # the same thing for total but add this logic 
     if type=="standard" : 
     total+=instance.z*100 
     return total 
+3

は申し訳ありませんが、あなたはここで任意の関数を呼び出していない、とあなたの最初の関数は、引数を1つしか取ります。 –

+0

私は、異なるユースケースで1つの関数を使用して、変数がロジックに追加されたときに同じコードを書くのを減らす方法を意味しました。 –

答えて

2

短い答えはい、しかし、そうでないかもしれないようにあなたは期待しています。 folowingを見て:あなたの例にこれを適用する

def fn(a, b, c= None): 
    if c is not None: 
     return a+b+c 
    else: 
     return a+b 

print fn(1,2,3) 
>> 6 
print fn(1,2) 
>> 3 

def get_shiff(instance, shift=None): 
    total=0 
    if shift is None: 
     if instance.x: 
      total+=instance.x/2 
     elif instance.y: 
      total.+=instance.y*40 
     return total 
    elif type=="standard" : 
     total+=instance.z*100 
     return total 
    else: 
     return 0 
関連する問題