我需要編寫一個具有以下條件的類構造函數:向量類構造函數參數
構造函數應該只帶一個參數。如果這個參數是一個int或一個long或從其中一個派生的類的一個實例,則認爲這個參數是Vector的長度。在這種情況下,構造一個具有指定長度的Vector,每個元素初始化爲0.0。如果長度爲負數,則用適當的消息提出ValueError
。如果參數不被認爲是長度,那麼如果參數是一個序列(例如list
),則使用具有給定序列長度和值的向量進行初始化。如果參數未用作向量的長度,並且它不是序列,則用適當的消息提出TypeError
。
我不知道怎麼寫相應的錯誤,我應該使用這個類錯誤:
class Failure(Exception):
"""Failure exception"""
def __init__(self,value):
self.value=value
def __str__(self):
return repr(self.value)
在交互式控制檯:
>>> Vector(3)
Vector([0.0, 0.0, 0.0])
>>> Vector(3L)
Vector([0.0, 0.0, 0.0])
>>> Vector([4.5, "foo", 0])
Vector([4.5, 'foo', 0])
>>> Vector(0)
Vector([])
>>> Vector(-4)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "vector.py", line 14, in __init__
raise ValueError("Vector length cannot be negative")
ValueError: Vector length cannot be negative
這裏是我的代碼。我只需要添加的錯誤,一個在if
語句時,它在else
聲明的int
或long
這是一個值誤差,以及一個用於TypeError
:
def is_sequence(obj):
try:
len(obj)
obj[0:0]
return True
except TypeError:
return False
class Vector:
l=[]
def __init__(self,object):
if(isinstance(object,long) |isinstance(object,int)):
x=int(object)
if(x<0):
else:
for i in range(0,x):
l.append(0.0)
elif(is_sequence(object)):
l.append(object)
else:
我不知道如何做這個。
SO不是「代碼寫入」服務,到目前爲止您嘗試過哪些代碼?你有什麼特別的問題? –
你應該向我們展示一些代碼_you_已經寫好,然後我們幫你修復它。 –