0

我正在制作的游戏中使用观察者模式进行测试。但是我遇到了一些问题。我的代码和错误如下,有人可以帮忙吗?

错误:

File "C:\Users\Administrator\PycharmProjects\untitled\Level.py", line 112, in update
    w.update()
  File "C:\Users\Administrator\PycharmProjects\untitled\Entity.py", line 13, in update
    self.notifyObservers()
  File "C:\Users\Administrator\PycharmProjects\untitled\Observable.py", line 15, in notifyObservers
    observer.update(self)
TypeError: unbound method update() must be called with Player instance as first argument (got WorldController instance instead)

级别文件:

self.world = [WorldController()]
for w in self.world:
            w.update()

实体文件:

class WorldController(Observable):
    def __init__(self):
        super(Observable, self).__init__()
        self._observers = []

    def update(self):
        self.addObserver(Player)
        self.notifyObservers()

class Entity(Observer, pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)

class Player(Entity, Observer):
    def __init__(self, x, y):
        super(Observer, self).__init__()
        Entity.__init__(self)
    def update(self, observable):
        print "works!"

可观察文件:

class Observable(object):
    def __init__(self, **kwds):
        super(Observable, self).__init__(**kwds)
        self._observers = []
    def addObserver(self, observer):
        if not observer in self._observers:
            self._observers.append(observer)
    def removeObserver(self, observer):
        try:
            self._observers.remove(observer)
        except ValueError:
            pass
    def notifyObservers(self):
        for observer in self._observers:
            observer.update(self)

class Observer(object):
    def __init__(self, **kwds):
        super(Observer, self).__init__(**kwds)
    def update(self, observable):
        pass
4

1 回答 1

1
class WorldController(Observable):
    def __init__(self):
        super(Observable, self).__init__()
        self._observers = []

    def update(self):
        self.addObserver(Player)
        self.notifyObservers()

应该:

class WorldController(Observable):
    def __init__(self):
        super(Observable, self).__init__()
        self._observers = []

    def update(self):
        self.addObserver(Player())
        self.notifyObservers()

否则,当您调用 Player.update(self) 时,您调用的是静态方法而不是 Player 类的实例方法

于 2013-03-02T18:33:00.633 回答