这是我的课FUN,但结果显示AttributeError: FUN instance has no attribute '__trunc__'
。请告诉我编码中的错误和修改内容。
import math
import random
import string
import numpy as np
import pickle
from itertools import chain
random.seed(0)
class FUN:
def __init__(self):
print "fun"
# set a random numbers between a & b
def rand(a, b):
self.rand = (b-a)*random.random() + a
return self.rand
# sigmoid function, tanh ~ 1/(1+e^-x)
def sigmoid(x):
self.sig = math.tanh(x)
return self.sig
def sigmoid1(x):
self.sig1 = 1/(1+math.exp(-x))
return self.sig1
# derivative of sigmoid function, in terms of the output (y)
def dsigmoid(y):
self.dsig = 1.0 - y**2
return self.dsig
# getting 2d array
#def matrix(I, J, fill=0.0):
#return [[val for col in range(I)] for row in range(J)]
#obtain a matrix
def matrix(I, J, fill=0.0):
m = []
for i in range(I):
m.append([fill]*J)
return m
f = FUN()
print f.matrix(2,3)
上面的代码给出了以下类型的错误:
fun
Traceback (most recent call last):
File "functions.py", line 42, in <module>
print f.matrix(2,3)
File "functions.py", line 38, in matrix
for i in range(I):
AttributeError: FUN instance has no attribute '__trunc__'
请帮我解决此错误。
答案 0 :(得分:7)
方法将self
参数作为第一个参数;您将其命名为I
并将其传递给range()
,然后FUN
会尝试将您的>>> class FUN: pass
...
>>> range(FUN())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: FUN instance has no attribute '__trunc__'
自定义类的实例转换为整数†。失败了:
self
添加 def matrix(self, I, J, fill=0.0):
参数:
__init__
您还需要为其他方法执行此操作;除了self
方法之外的所有方法都缺失object.__trunc__
。
† Python首先尝试object.__int__
,然后尝试{{1}},这种方法令人惊讶地未被记录。只有math.truncate()
文档和Numbers Type Hierarchy PEP 3141 proposal提及方法。