r/pythonhelp • • Aug 14 '22

Grab item from class without knowing what the item is?

I'm trying to make a system that requires picking an object from a class where the object depends on the players input. I tried something like this:

class items:
    class IronSword:
        name = "Iron sword"
        value = 20
        description = "whatever lololol"

c = IronSword
itemtheplayerpicksorwhatever = items.c.value

But this gives me an attribute error because c is not an item in the class. How could I do this?

2 Upvotes

3 comments sorted by

1

u/DaaxD Aug 14 '22 edited Aug 14 '22

Because you never created an instance of the class.

In addition, you might want to some additional research on what classes actually are, because the way you wrote your example tells me that you do not know exactly what classes are and what they are used for.

There are better tutorials for this compared to the official documentation, but that should be your first place to look from. Google can help you finding more educational tutorials.

TLDR, classes are way to bundle values and functionality together. When you create a class, you create a new datatype which has both data and functionalities attached to it. Once you have declared your class, ie. wrote what the class is and what it can do, you can now create insances of that class and use them in your code.


I'm going to have some fun with the classes here so that you can get a better idea what classes are used for.

First, I'm going to write now a class Weapon with a constructor. Constructor is a function that assigns the desired values to the differenet fields and variables which class happends to have.

class Weapon:
    def __init__(self, name, damage, say):
         self.name = name
         self.damage = damage
         self.say= say

    def describe(self):
        print(f"This weapon is called {self.name} and It deals {self.damage}. It goes {self.say}")

Now we have a class for weapons, but we don't have single weapon created yet. Let's create few and inspect them a little.

axe = Weapon("Axe", 100, "Choppy Choppy")
mace = Weapon("Mace", 50, "BONK BONK!")
sword = Weapon("Iron Sword", 20, "whatever lololol")
axe.describe()
mace.describe()
sword.describe()

If we want to store this objects to somewhere, it would be much more useful to use normal data stores for it (lists, dictionaries, what not)

equipment = {
    axe.name: axe,
    mace.name: mace,
    sword.name: sword
}
current_weapon = equipment["Axe"]
print(f"Your current weapon is {current_weapon.name}")
print("Choose your weapon from the following:")
for item in equipment:
    print(item, equipment[item].damage)
player_choise = input(">")
if player_choise in equipment:
    current_weapon = equipment[player_choise]
    print(f"Your current weapon is {current_weapon.name}")
else:
    print(f"You do not have {player_choise} (remember capital letters)")

And if you want to test if something is a Weapon or not, you can use isinstance function.

if isinstance(sword, Weapon):
    # sword is a weapon
    print("A fine weapon you have there. Go whack some baddies!")
else:
    print("You can't use that as a wepaon!")

if isinstance(10, Weapon):
    print("A fine weapon you have there. Go whack some baddies!")
else:
    # 10 is not a weapon
    print("You can't use that as a wepaon!")

if isinstance("Spear", Weapon):
    print("A fine weapon you have there. Go whack some baddies!")
 else:
    # "Spear" is not a weapon either.
    print("You can't use that as a wepaon!")

The last one is not a weapon, but a string which just says "spear". It doesn't make it an instance of the Weapon class.

if isinstance("Spear", str):
    print('"Spear" is a string')
if not isinstance(axe, str):
   print("axe is not a string!")

1

u/RealMuffinsTheCat Aug 15 '22

I now have this:

class items:
def __init__(self, name, value, description):
	self.name = name
	self.value = value
	self.description = description

IronSword = items("iron sword", 20, "A standard iron sword. Does 10 damage per hit.")

The items are in a separate file to make things easier to navigate. Would it be easier to put it all into one file or is there a way to get to it from a separate file? Because when I import the file it's treated as it's own class.

1

u/DaaxD Aug 15 '22 edited Aug 15 '22

I can't answer to that question for sure, because I don't know your file structure or how you are using the files in your program. However, if your items are actually as simple as you have written here, then you could write all your items in a single csv file...

items.csv

Axe, 100, Choppy Choppy
Mace, 50, BONK BONK!
Iron Sword, 20, whatever lololol

Code that reads the file...

items = {}
with open('items.csv', 'r') as f:
    for line in f:
        # NOTE, if your descriptions uses commas, then using line.split apply split to these commas too.
        # I'll leave figuring out more sophisticated method as a homework ;)
        line = line.split(',') 
        # Note, when you read a file, the number is intepreted as a string.
        # This is why it's converted to a number here with the int() function.
        # Are all your values integers or is there real numbers mixed in too?
        item = Item(line[0], int( line[1] ), line[2]) 
        items[item.name] = item

I have other suggestions as well, which might sound like minor nitpicks, but trust me that these will help you a lot in a long run.

Please name your class Item instead of items. There are two reasons for this

  1. First thing is the singular vs plural. If we consider the line

    IronSword = items("iron sword", 20, "A standard iron sword. Does 10 damage per hit.")

you are not really creating many items. You are creating an item. Therefore, it would look and sound more natural if the code said that IronSword is an item, instead of saying that IronSword is items.

IronSword = Item("iron sword", 20, "A standard iron sword. Does 10 damage per hit.")

Furthermore, when you write

class Item

It would be much clearer that you are describing what an item is and what are it's properties and functions. The naming convention in your OP was one of the telltale signs that you were a bit confused what classes are.

Other reason is that when you name only collections with plurals, then you can immediately recognize if the variable is a container or the item itself.

For example, if you take a look at the example above where I read the csv file and created the items listed in the csv file. You can probably tell quite easily when I'm referring to the dictionary of items and when I'm referring to the individual items. The example would've turned much more harder to read, if I couldn't use items as a name of the dictionary of, well, items.

2) Capitalization. Nothing stops you from using capital case in variable names and minor case in class names, but FYI, rest of the programming world uses a convention where variable names are with minor case, and class names and other type defintions are capitalized. In fact, the Pythons official style guide also suggests to using capitalized class names.

Or if you look at the previous example again, you will see that the word Item clearly stands out from the other variables and function calls, which are written in lower case. If your naming convention is consistent enough, then you don't need to read the declarations to know what is the difference between item, Item and items.

However, the most important rule of the naming conventions is have a consistnent naming scheme throughout the whole project. If you have already capitalized every single variable name and used smaller case for the classes in your project, then you might as well stick to it. Just be aware that rest of the programming world is not going to agree with your naming scheme :)