如何为类中的变量分配类型/值

2024-09-28 03:22:27 发布

您现在位置:Python中文网/ 问答频道 /正文

在这里,我尝试制作一个具有以下特性的对象(一个20面模具);名称和边数。你知道吗

我想要构建这个类的方法是,当我调用这个类(或者创建一个新的“Dice”对象)时,我只需要告诉代码该如何命名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.

Tags: theto对象nameselfthatisrange
2条回答

在解析“range”类时,出现了一个新的Int类对象,而不是整数。但是,还有其他错误,例如尝试调用字符串对象:name(“”),这不应该起作用。你知道吗

您的init类可以修改为:

def __init__(self, name, nsides):

    self.name = name
    self.nsides = list(range(*nsides)) 

“*”将把元组解压成可供range类使用的整数

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]

相关问题 更多 >

    热门问题