如何从班级中的列表中随机选择

时间:2016-11-16 17:19:26

标签: python random

我想随机选择一个武器,我想写出它的名字,但结果不像我期望那段代码有什么问题?

import random
class Dusman:
    def __init__(self,name='',weapon='',armor=''):
        self.name= name
        self.weapon= weapon
        self.armor= armor

    def name(self):
        a=name
        a = input("Write a name: ")

    def weapon(self):
        weapon=["Sword","Axe","Topuz"]
        print(random.choice(weapon))


    def print(self):
        print("Name",self.name,"Weapon: ",self.weapon,"Armor: ",self.armor)

dusman1=Dusman()
dusman1.name
dusman1.weapon
dusman1.print()

2 个答案:

答案 0 :(得分:0)

目前,您只打印选项。

您需要将选择的结果设置为weapon实例变量:

def weapon(self):
    weapons = ["Sword", "Axe", "Topuz"]
    self.weapon = random.choice(weapons)

答案 1 :(得分:0)

这是您的预期结果吗?

import random

class Dusman:
    def __init__(self,name='',weapon='',armor=''):
        self._name= name
        self._weapon= weapon
        self._armor= armor

    def name(self):
        self._name = input("Write a name: ")

    def weapon(self):
        weapons=["Sword","Axe","Topuz"]
        self._weapon = random.choice(weapons)
        print(self._weapon)

    def __str__(self):
        return "Name: {0} Weapon: {1} Armor: {2}".format(self._name,
                                                         self._weapon,
                                                         self._armor)

if __name__ == '__main__':
    dusman1=Dusman()
    dusman1.name()
    dusman1.weapon()
    print(dusman1)

您的问题是,您有命名冲突。您将变量命名为与函数相同。