I create a simple text quest with random events, which accumulated a lot, and I decided to separate them into a separate class. But after that I got a problem. It doesn't look complicated, but I can't find a solution.
import random
class Hero:
def __init__(self, name):
self.name = name
hero1 = Hero('Bob')
class RandEvents:
def __init__(self, hero):
self.hero = hero
def event1(self):
print(f'>>> {self.hero.name} text 1 event! <<<')
def event2(self):
print(f'>>> {self.hero.name} text 2 event! <<<')
list_events = [RandEvents.event1, RandEvents.event2]
event = random.choice(list_events)
event(hero1)
I get
File "E:\1.py", line 17, in event1
print(f'>>> {self.hero.name} text 1 event! <<<')
^^^^^^^^^
AttributeError: 'Hero' object has no attribute 'hero'
I tried to create a function rand_event()
, and move it to a class Hero
or RandEvents
. To no avail.
Fixed:
import random
class Hero:
def __init__(self, name):
self.name = name
hero1 = Hero('Bob')
class RandEvents:
def __init__(self, hero):
self.hero = hero
def event1(self):
print(f'>>> {self.name} text 1 event! <<<')
def event2(self):
print(f'>>> {self.name} text 2 event! <<<')
list_events = [RandEvents.event1, RandEvents.event2]
event = random.choice(list_events)
event(hero1)