Bottom Page

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
 Some help with Classes and the random module please? :)
#1
So, I want to create a class, that has a few items inside. (sorry if I don't use the correct terms I'm new to Python)

class Basic():
    def __init__(self, item, attack, sell_price, buy_price):
    self.item = item
    self.attack = attack
    self.sell_price = sell_price
    self.buy_price = buy_price

basic_sword = basic('basic Sword', 10, 50,25)
basic_spear = basic('basic spear', 15, 25, 30)
basic_gloves = basic('basic gloves', 5, 8, 10)
basic_knife = basic('basic knife', 10, 25, 35)

starting_crate = [basic_sword, basic_spear, basic_gloves, basic_knife]
So, how would I go about getting a random object from the starting_crate list and print out ONLY the item name part using the random module?

for example:
You opened basic crate and got a basic sword!

rather than:
<__main__.basic object at 0x7efec00d9450>

Thanks!
Quote
#2
import random
...
print(random.choice(starting_crate).item)
or
print('You opened basic crate and got a {}'.format(random.choice(starting_crate).item))
random.choice(starting_crate) returns one random object from that list. If it selected basic sword object then it really selected basic_sword object so to get the name (in which you called item) would be basic_sword.item
Quote
#3
Thank you! you're awesome!
Quote

Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  Can't Get Random Module! Pls Help! VictorVictus 1 979 Aug-24-2019, 10:20 AM
Last Post: snippsat
  Question about the Random Module Exsul 1 457 Mar-13-2019, 02:06 AM
Last Post: ichabod801
  Random module Python 3.6 daryl_uk 1 638 Oct-25-2018, 12:09 AM
Last Post: micseydel
  Random module works in idle but not terminal. ottowiser 3 2,102 Apr-11-2018, 10:59 PM
Last Post: ottowiser
  Using classes? Can I just use classes to structure code? muteboy 5 1,776 Nov-01-2017, 04:20 PM
Last Post: metulburr
  random module in while loops yuvalsaias 8 2,601 Feb-03-2017, 03:10 PM
Last Post: wavic

Forum Jump:


Users browsing this thread: 1 Guest(s)