Python print 的时候出现<__main__.Observer object at 0x0224F3B0>
PHP中文网
PHP中文网 2017-04-17 15:14:05
0
2
579

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℃
今日建议:请注意别感冒!

请问这是什么原因,以及解决之道

PHP中文网
PHP中文网

认证高级PHP讲师

Antworte allen(2)
巴扎黑
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时的返回值

迷茫

在Class Observer的init函数中,self.subject.add_observer(self)语句将Weather的实例对象append到Weather的observers list里面了。

Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!