Python 如何正确调用类
我是一个Python新手(一般来说也是编程新手),我正在尝试制作一个基于文本的、无休止的rpg,其中包含基于列表的随机房间/遭遇。这段代码(当然)还没有完成,只是为了测试。请注意,我从另一个.py文件导入了敌人:Python 如何正确调用类,python,python-3.x,Python,Python 3.x,我是一个Python新手(一般来说也是编程新手),我正在尝试制作一个基于文本的、无休止的rpg,其中包含基于列表的随机房间/遭遇。这段代码(当然)还没有完成,只是为了测试。请注意,我从另一个.py文件导入了敌人: import Enemies import random class Room: # template definition to define all rooms def __init__(self, intro): self.intro = in
import Enemies
import random
class Room:
# template definition to define all rooms
def __init__(self, intro):
self.intro = intro
class VsRoom(Room):
# room with an enemy
def __init__(self, enemy):
self.enemy = random.choice(Enemy_List)
super().__init__(intro = "There's an enemy here!")
class NullRoom(Room):
# empty, boring room
def __init__(self):
super().__init__(intro = "Nothing Interesting here.")
Rooms = [VsRoom, NullRoom] # All future room "types" will go here
def print_room():
# Tells the player which kind of room they are
print("You enter the next room...")
Gen_Room = random.choice(Rooms)
print(Gen_Room.intro)
我希望print room()打印“你进入下一个房间…”,从列表中随机选择一个房间,然后打印它的简介,但当我尝试运行它时,我得到以下结果:
You enter the next room...
[...]
print(Gen_Room.intro)
AttributeError: type object 'NullRoom' has no attribute 'intro'
Process finished with exit code 1
我正在努力学习如何上课,任何帮助对我都是非常好的。我试着尽可能地遵循PEP8,也试着找到类似的问题,但没有成功。从我观察到的情况来看,你有一个选择敌人的列表,因此你不需要输入该参数:
class VsRoom(Room):
# room with an enemy
def __init__(self):
self.enemy = random.choice(Enemy_List)
super().__init__(intro = "There's an enemy here!")
要创建实例,必须按以下步骤执行:
{class name}()
所以你必须改变:
Gen_Room = random.choice(Rooms)
致:
完整代码:
import Enemies
import random
class Room:
# template definition to define all rooms
def __init__(self, intro):
self.intro = intro
class VsRoom(Room):
# room with an enemy
def __init__(self):
self.enemy = random.choice(Enemy_List)
super().__init__(intro = "There's an enemy here!")
class NullRoom(Room):
# empty, boring room
def __init__(self):
super().__init__(intro = "Nothing Interesting here.")
Rooms = [VsRoom, NullRoom] # All future room "types" will go here
def print_room():
# Tells the player which kind of room they are
print("You enter the next room...")
Gen_Room = random.choice(Rooms)()
print(Gen_Room.intro)
您在
def\u init\u(self,敌方)中使用敌方时,敌方列表的值是什么?
敌方列表是来自另一个名为敌方
的.py文件的列表。在def\u init\u(self,敌人):
中存在敌人是不必要的,如下所述。谢谢,它现在起作用了。我还忘了键入敌人。敌人列表而不是敌人列表。
import Enemies
import random
class Room:
# template definition to define all rooms
def __init__(self, intro):
self.intro = intro
class VsRoom(Room):
# room with an enemy
def __init__(self):
self.enemy = random.choice(Enemy_List)
super().__init__(intro = "There's an enemy here!")
class NullRoom(Room):
# empty, boring room
def __init__(self):
super().__init__(intro = "Nothing Interesting here.")
Rooms = [VsRoom, NullRoom] # All future room "types" will go here
def print_room():
# Tells the player which kind of room they are
print("You enter the next room...")
Gen_Room = random.choice(Rooms)()
print(Gen_Room.intro)