我正在尝试用Python制作面向对象的文本游戏,并尝试实现我的第一个属性和装饰器。使用书籍'Python 3面向对象编程'中的第5章,我试图使用讨论的示例和概念来设置Game对象的“current_room”属性:
class Room(object):
''' An area of the game's map.'''
def __init__(self):
print("Accessing the Room __init__ method.")
class FirstRoom(Room):
''' Just some room.'''
def __init__(self):
print("Accessing the FirstRoom __init__ method.")
super.__init__()
class SecondRoom(Room):
''' Just some other room.'''
def __init__(self):
print("Accessing the SecondRoom __init__ method.")
super.__init__()
class Game(object):
''' Creates a new game.'''
current_room = None # Class-level definition of this property.
def __init__(self):
print("Created a new Game object.")
self.current_room = FirstRoom()
@property
def current_room(self):
''' Returns the current position of the actor.'''
print("Getting the _current_room attribute for the Game object.")
return self._current_room
@current_room.setter
def set_room(self, new_room):
''' Sets the current_room property of the Game object.'''
print("Setting the _current_room attribute for the Game object.")
self._current_room = new_room
然而,当我运行此代码时,我得到了以下输出:
>>> g = Game()
Created a new Game object.
Accessing the FirstRoom __init__ method.
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/drew/Desktop/test.py", line 27, in __init__
self.current_room = FirstRoom()
File "/home/drew/Desktop/test.py", line 11, in __init__
super.__init__()
TypeError: descriptor '__init__' of 'super' object needs an argument
我需要在代码中添加什么才能使这个语法生效? 我需要明确定义“current_room”属性的描述符吗?[至少书中没有提到任何关于描述符的内容,就像你在这里找到的Python Descriptors Demystified一样。]
super
。 - user2357112super
,而你链接的问题确实调用了super
,产生的错误也非常不同。 - Bakuriu