class Observer(object):
def __init__(self,subject):
self.subject = subject
self.weather = self.subject.weather
self.subject.add_observer(self)
def update(self,weather,temperature,tips):
self.weather = weather
self.temperature = temperature
self.tips = tips
self.display()
def display(self):
return ("今日天气:{} \n今日气温: {} \n今日建议:{}").format(self.weather,self.temperature,self.tips)
class Weather(object):
def __init__(self):
self.observers = []
self.weather = ""
self.temperature = ""
self.tips = ""
def add_observer(self,observer):
self.observers.append(observer)
def delete_observer(self,observer):
if observer in self.observers:
self.observers.remove(observer)
def notify(self):
for observer in self.observers:
observer.update(self.weather,self.temperature,self.tips)
def add_data(self,weather,temperature,tips):
self.weather = weather
self.temperature = temperature
self.tips = tips
self.notify()
if name=='main':
subject= Weather()
observer = Observer(subject)
subject.add_data('多云转阴','10~23℃','请注意别感冒!')
subject.add_observer('张三')
subject.add_observer('李四')
subject.add_observer('Ben')
def Print():
ox = subject.observers
for o in ox:
weather_data = observer.display()
print("{}你好,以下是今日的天气播报:\n{}\n").format(o,weather_data)
Print()
初学Python,在做观察者模式的时候发现print会打印出多余的东西
<main.Observer object at 0x0224F3B0>你好,以下是今日的天气播报:
今日天气:多云转阴
今日气温: 10~23℃
今日建议:请注意别感冒!
请问这是什么原因,以及解决之道
巴扎黑2017-04-17 15:16:05
observer = Observer(subject)
self.subject.add_observer(self)
使得observer被添加到subject.observers中去
print("{}你好,以下是今日的天气播报:\n{}\n").format(o,weather_data)
o就是observer,print observer
所以会输出<main.Observer object at 0x0224F3B0>
可以看一下“__str__”方法,可以修改print observer时的返回值
迷茫2017-04-17 15:16:05
在Class Observer的init函数中,self.subject.add_observer(self)语句将Weather的实例对象append到Weather的observers list里面了。