Burak Fidan Burak Fidan - 18 days ago 7
Python Question

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

Answer

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.

Comments