简体   繁体   中英

How to Randomly pick from list in the class

I want to randomly pick a weapon and i want to write the name of it but the result is not like i expect what is wrong in that code?

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()

Currently, you only print the choice.

You need to set the result of the choice to the weapon instance variable:

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

Is this your expected result?

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)

Your problem is, that you have naming collisions. You are naming a variable the same as a function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM