r/pythonhelp • u/RealMuffinsTheCat • 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.valueBut this gives me an attribute error because c is not an item in the class. How could I do this?
2
Upvotes
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.
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.
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)
And if you want to test if something is a Weapon or not, you can use isinstance function.
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.