在这里,我正在尝试制作具有以下品质的物体(一个20面的模具);名称和边数。
我要构建它的方式是,当我调用类(或创建一个新的“ Dice”对象)时,我只需要告诉代码是什么来命名骰子,以及骰子上有多少面。 (在这种情况下为1到20。)
class Dice: #The class itself, the outline for the Dice to come.
def __init__(self, name, nsides):
#The initializing bit, along with
#the stats I want these objects to carry.
self.name = name("")
self.nsides = nsides(list(range(int, int)))
#I was thinking the above code tells python that the value nsides,
#when referencing Dice, is a list, that is being organized into
#a range, where the items in said range would always be integers.
d20 = Dice("d20", (1, 21))
#This is where I'm creating an instance of Dice, followed by filling out
#the fields name and the integers in nsides's list/range.
print(d20.nsides)
print(d20.nsides)
#The expected outcome is the following being printed:
#[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
#What I get however is this error upon running:
#Expected type 'int'. got 'Type[int]' instead.
答案 0 :(得分:2)
您在将“ range”类解析为新的Int Class对象而不是整数时发生错误。但是,还有其他错误,例如尝试调用字符串对象:name(“”)无效。
您的init类可以修改为:
def __init__(self, name, nsides):
self.name = name
self.nsides = list(range(*nsides))
“ *”会将元组解压缩为可用的整数,以供范围类使用
答案 1 :(得分:0)
class Dice: #The class itself, the outline for the Dice to come.
''' param:
name : str # name to given,
nsides : tuple/ list iterateable variable
return: None
'''
def __init__(self, name, nsides):
# passing the name (user input ) to class object self.name
self.name = name
# doing list comprehension
self.nsides = [ i for i in range(nsides[0],nsides[1])]
# range function works as range(a,b)-> [a,b) a is incluse and b is exclusive
# and it is incremented by 1 default
''' it is same as
self.nsides = []
for i in range(nsides[0],nsides[1]):
self.nsides+=[i] # or self.nsides.append(i)
'''
d20 = Dice("d20", (1, 21))
print(d20.nsides)
# output [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]