如何自动创建类的实例?

时间:2018-04-13 23:21:10

标签: python python-3.x oop

所以在python 3中,我无法自动创建类的多个实例。我试图垄断,这里是给我问题的代码示例。

def numplayer():
    numplayer = int(input('How many players would you like? (up to four)'))
    while numplayer > 4 or numplayer < 1:
        numplayer = int(input('How many players would you like? (up to 
        four)'))
    for i in range(numplayer):
        PlayerMoney.append(1500)

我想要做的是添加一些东西,这些东西会在for i in range(numplayer)函数中创建numplayers等于的玩家数量。我让玩家成为一个班级,但我不想为每个玩家手动创建每个班级。如果有解决方案,请告诉我们。谢谢!

编辑:所以我认为这可能是标题中的错误措辞,但我试图创建单个类(播放器)的多个实例。 以下是播放器类的代码:

class Player:

    def __init__(self, name, money, position):
        self.name = name
        self.money = money
        self.position = position

    def DiceRoll(self):
        x = random.randint(1, 6)
        y = random.randint(1, 6)
        sum = x + y
        return [sum, x, y]

    def getName(self):
        return sef.name

    def getMoney(self):
        return self.money

    def getPosition(self):
        return self.position

2 个答案:

答案 0 :(得分:1)

我建议您按如下方式构建代码。你的函数通常是一个好主意return

def setup():

    n = int(input('How many players would you like? (up to 4)'))

    names = [input('Give name #{0}'.format(i)) for i in range(1, n+1)]

    return [Player(name, 1500, 0) for name in names]

players = setup()

答案 1 :(得分:0)

# Create Class 
class Player:
    def greating(self):
        print 'Hello!'

# List to store instanses
l = []

for i in range(4):
   l.append(Player())

# Call Instance #1 methods
l[0].greating()

这里我们有一个玩家类,这个类中有4个实例存储在l list中。