简体   繁体   中英

how to call a function in python with different number of attributes and with another logic?

I have a function in python that has 2 arguments: for example

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

Can I call this function in python in another file as this:

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

Short answer Yes, but maybe not as you expect. Have a look at the 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

Applying this to your example:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM