为什么type()函数在这里不起作用?

我正在学习Python,并且试图查看函数的行为是否符合我的预期。但是,我遇到了一个问题:

import numpy as np

def test():
     return np.array([1, 2, 3])

type(test())

I would expect the output to be numpy.ndarray. However, I get nothing when I run this script.

I have tried different things instead of the type function; for example, print(test()) worked as expected. But for some reason the type function doesn't seem to work. Could you please enlightment me as to why? Thanks!

评论
  • trerum
    trerum 回复

    有两件事:

    1. 您必须打印输出
    2. 有两种不同的情况:
    import numpy as np
    
    def test():
         return np.array([1, 2, 3])
    
    print(type(test))
    print(type(test()))
    
    

    首先会打印“类'功能'”的实际测试类型

    第二个(您的情况)实际上会调用该函数(因为您将其写为wih(),所以是test()),因此将对返回值进行求值,而type将返回结果的类型,此处为“ class'numpy .ndarray'”

  • uet
    uet 回复

    You need to print the output of test to be able to see it. Try this:

    import numpy as np
    
    def test():
         return np.array([1, 2, 3])
    
    print(type(test()))
    

    编辑:在Python的交互式控制台中,您无需打印内容就可以查看其输出,因此可能会使您有点失望:|