Python/Pygame Creating Random Monsters with Random Attributes from Class/Method
I Am Attempting to Create a Text Based Rpg. I Want to Use a Class Monsters to Create a Random Monster of a Particular Type. However I Cannot Seem to Access the...
I am attempting to create a text based RPG. I want to use a Class Monsters to create a random monster of a particular type. However I cannot seem to access the random variables associated with the method in the class. Here is a trimmed down version of the code:
import random
class Monsters():
def wolfEnemy(self):
self.hp = random.randint(10, 20)
self.attk = random.randint(1, 3)
self.gold = random.randint(2, 5)
self.xp = 100
monsters = Monsters()
print(monsters.wolfEnemy)
things = monsters.wolfEnemy.hp()
print(things)
I'm not sure how to access variables from within a instantiated method. print(monsters.wolfEnemy) just produces None and things = monsters.wolfEnemy.hp() errors with builtins.AttributeError: 'function' object has no attribute 'hp'. Is there a way to call up that wolfEnemy and the attributes outside the Class/Method.
2 Answers
Define a WolfEnemy class that inherits from the Monster class. In the Monster class you can define attributes and methods that every subclass should have, and override them to create the specific subclasses.
import random
class Monster:
def __init__(self):
self.hp = random.randint(10, 20)
self.attk = random.randint(1, 3)
self.gold = random.randint(2, 5)
self.xp = 100
class WolfEnemy(Monster):
def __init__(self):
# Call the __init__ method of the parent class, that means the
# wolf instance will get the attributes that we've defined there.
super().__init__()
# To override specific attributes, assign new values here.
self.hp = random.randint(20, 30)
wolf = WolfEnemy()
print(wolf.hp)
you can get the result you want like this:
import random
class Monsters():
def wolfEnemy(self):
self.hp = random.randint(10, 20)
self.attk = random.randint(1, 3)
self.gold = random.randint(2, 5)
self.xp = 100
monsters = Monsters()
# wolfEnemy() for the function call not wolfEnemy
monsters.wolfEnemy()
# monsters.hp get the attr not monsters.wolfEnemy.hp()
print(monsters.hp)