Python Forum
Some help with Classes and the random module please? :) - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Some help with Classes and the random module please? :) (/thread-23619.html)



Some help with Classes and the random module please? :) - AlluminumFoil - Jan-08-2020

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!


RE: Some help with Classes and the random module please? :) - metulburr - Jan-08-2020

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


RE: Some help with Classes and the random module please? :) - AlluminumFoil - Jan-08-2020

Thank you! you're awesome!