如何计算函数中变量的数量 - Python

问题描述 投票:0回答:2

我希望能够编写一个函数来计算函数中参数的数量,例如:

计数器(“一”,“二”)

2

计数器(“一”,“二”,“三”)

3

等等,

到目前为止我已经有了这个,但我不确定它是否正确。有人可以帮我解决这个问题吗?谢谢。

def counter(f):
    f.counter = 0
    def counting_f(*args):
        v = f(*args)
        f.counter += 1
        print("{0}: {1} times".format(f.__name__, f.counter))
        return v
    return counting_f
python function arguments decorator counting
2个回答
0
投票

不确定你想要什么。是这个吗:

def counter(*f):
  print len(f)

>>> counter("one", "two")
2

>>> counter("one", "two","three")
3

0
投票

几周前,我遇到了一个非常“强大”的d_word/魔术词,称为code。 一旦访问,它就会解锁各种属性,您可以通过这些属性找到有关您的类/方法/实体结构的信息。

因此,我将允许自己重新设计你的代码......

@staticmethod
def counting_f(arg1:str = "", arg2:str = "", arg3:str = ""):
    print(counting_f.__code__.co_argcount)

我想说更优雅。 只要我没有误解你的标记问题...

© www.soinside.com 2019 - 2024. All rights reserved.