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)
Causes the observer to be added to subject.observers
print("{}你好,以下是今日的天气播报:\n{}\n").format(o,weather_data)
o is observer, print observer
So it will output <main.Observer object at 0x0224F3B0>
You can take a look at the "__str__" method and modify the return value of print observer
迷茫2017-04-17 15:16:05
In the init function of Class Observer, the self.subject.add_observer(self) statement appends the instance object of Weather to the Weather observers list.