【问题标题】:how to get rid of Nontype array如何摆脱非类型数组
【发布时间】:2021-02-19 10:21:54
【问题描述】:
我想要一个包含随机二进制值的数组,它的长度是 p,但是我得到了错误:
AttributeError: 'NoneType' 对象没有属性 'type'
这是我的代码
import random
def length(p):
binary = []
for i in range(p):
temp = random.randint(0, 1)
binary.append(temp )
print(binary)
fn=length(5)
fn.type
【问题讨论】:
标签:
python
arrays
list
random
binary
【解决方案1】:
length 没有 return 语句,所以它不能返回任何东西。当 Python 中的函数不返回任何内容时,尝试将变量设置为其返回值会将变量设置为 None。因此,something=length(something_else) 等价于something=None。因此,None.type 将失败,因为 None 单例没有 type 属性。
解决方案是在您的函数中添加一个返回语句。您可能打算将return binary 添加到末尾。但是 list 仍然没有 type 属性。您可能打算使用type(fn),这是 Python 中获取某物类型的正确方法。
【解决方案2】:
嗨,首先你没有返回任何值
def length(p):
binary = []
for i in range(p):
temp = random.randint(0, 1)
binary.append(temp )
print(binary)
return binary # Add return here
第二种是这样使用的
fn.type # Change this
type(fn) # To this