Python Forum
Some help with Classes and the random module please? :)
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!
Reply
#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
Recommended Tutorials:
Reply
#3
Thank you! you're awesome!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  <while> cycle is not interrupted when using the <random>module ShityCoder 3 2,105 Sep-04-2020, 04:05 PM
Last Post: ShityCoder
  Can't Get Random Module! Pls Help! VictorVictus 1 7,052 Aug-24-2019, 10:20 AM
Last Post: snippsat
  Question about the Random Module Exsul 1 1,964 Mar-13-2019, 02:06 AM
Last Post: ichabod801
  Random module Python 3.6 daryl_uk 1 2,209 Oct-25-2018, 12:09 AM
Last Post: micseydel
  Random module works in idle but not terminal. ottowiser 3 5,456 Apr-11-2018, 10:59 PM
Last Post: ottowiser
  Using classes? Can I just use classes to structure code? muteboy 5 4,978 Nov-01-2017, 04:20 PM
Last Post: metulburr
  random module in while loops yuvalsaias 8 6,486 Feb-03-2017, 03:10 PM
Last Post: wavic

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020