Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Simple problem with Class RandomEvent in Python

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading