2017-05-25 68 views
0

標題說明了 - 如果我有這樣的一個函數,要改變(打印輸出等)做什麼我除了重新定義???:改變python的功能,而不是重新定義它們?

import sys 
def UselessFunction(Weight, WeightIncrease): 
    for Year in range(0, 16): 
     Weight = Weight + WeightIncrease 
     Weight_On_Moon = Weight * 0.165 
     print('Your weight on the moon would be %s in the year %s' % (Weight_On_Moon, Year)) 
     Weight = Weight + 1 

想要改變「你的體重上那麼......「到」在月球上你會比在地球上輕一點!事實上,你只會在年%s'%(Weight_On_Moon,Year)中體重%s kg)

感謝所有人

+0

您可以將回調作爲參數傳遞。否則,您可以返回兩個值並以不同的函數打印輸出 – zanseb

+0

您可以...(這裏是DRAGONS!)...重寫'print()'並在事實之後進行替換。但不要這樣做,這是一個非常糟糕的主意,如果你這樣做了,千隻小貓就會死亡。 – zwer

+0

即時通訊新的蟒蛇 - 你如何傳遞一個回調作爲參數或在不同的功能打印輸出?謝謝 –

回答

0

這是一個hokey的例子:

class ResultHandler(object): 
    def __init__(self, output_str): 
     self.output_str = output_str 
    def handler(self, results): 
     print self.output_str % (result[0], result[1]) 

def handle_output(func, args, callback): 
    # compute moon weight and year 
    results = func(*args) 

    # Invoke the callback with the result 
    # Specifc to this problem 
    try: 
     for result in results: 
      callback(result) 
    except TypeError: 
     pass 

# Try it here 
r1 = ResultHandler('Your weight on the moon would be %s in the year %s') 
r2 = ResultHandler('On the moon you would be way lighter than on Earth! In fact, you would only weigh %s kg in the year %s') 
handle_output(UselessFunction, (12, 3), callback=r1.handler) 
handle_output(UselessFunction, (12, 3), callback=r2.handler) 
相關問題