【问题标题】:in Python, how do I inspect the type/length of values returned by a function or method?在 Python 中,如何检查函数或方法返回的值的类型/长度?
【发布时间】:2019-11-14 14:10:22
【问题描述】:

假设我有一个类Test,其属性为names,方法为calculate

class Test:
    def __init__(self, names=('square', 'cube')):
        self.names = names

    def calculate(self, x):
        return x**2, x**3

是否有一种简单的方法可以确定传递的名称数量等于calculate 返回的值的(可变)数量,而无需实际通过该方法传递数据?基本上我只想要求类定义在实现时是一致的。

类似于额外的一行:

    # check that calculate output and names line up
    # help needed here
    assert len(self.names) == # length of output of self.calculate  

【问题讨论】:

    标签: python-3.x oop inspect


    【解决方案1】:

    计算返回的值的数量实际上没有通过该方法传递数据

    如果不调用calculate(),我能看到的唯一解决方案就是提前知道它正好返回两个值,因此assert len(self.names) == 2

    如果calculate() 可以返回任意数量的值,我不知道您如何避免调用它。

    【讨论】:

    • 嗯,我担心可能是这种情况。我希望可能有一些类似于transform.__code__.co_argcount(用于参数数量)的内部结构给出输出数量
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-13
    • 2023-03-17
    • 2019-07-12
    相关资源
    最近更新 更多