在python中更改函数而不是重新定义它们?

2024-05-20 10:26:41 发布

您现在位置: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年的重量仅为%s千克(月球上的重量,年))

谢谢大家


Tags: theinimport功能标题定义on地址
1条回答
网友
1楼 · 发布于 2024-05-20 10:26:41

下面是一个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)

相关问题 更多 >