英文:
Simple problem with Class RandomEvent in Python
问题
我创建了一个带有随机事件的简单文本冒险游戏,这些事件积累了很多,我决定将它们分离到一个单独的类中。但之后我遇到了一个问题。看起来并不复杂,但我找不到解决办法。
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)
我得到
File "E:.py", line 17, in event1
print(f'>>> {self.hero.name} text 1 event! <<<')
^^^^^^^^^
AttributeError: 'Hero' object has no attribute 'hero'
我尝试创建一个名为rand_event()
的函数,并将其移到Hero
或RandEvents
类中。但是没有成功。
英文:
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:.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.
答案1
得分: 1
固定:
```python
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)
<details>
<summary>英文:</summary>
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)
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论