Question

How do I make my code print out the text in the ServiceNotifier class? Python Code:...

How do I make my code print out the text in the ServiceNotifier class?

Python Code:

class ServiceNotifier:
#Subject responsible for notifying registered observer objects

   Observer = [Email, SMS, Phone]
  
   def attach(self):
   #add new observer
       Observer.append(insertnewobserverhere)

   def dettach(self):
   #remove an observer
       Observer.pop(insertnewobserverhere)

   def servicenotifier(self):
       for observers in Observer:
           print("Due to the forecast for tomorrow, all university and campus operations will be closed.")
      

##########################################################

def Service():
#Main code to execute
   for alerts in ServiceNotifier():
       notify = alerts.servicenotifier()
       return notify

if __name__ == "__main__":
#Exectues the weather alert system
   Service()

0 0
Add a comment Improve this question Transcribed image text
Answer #1

The problem with your code is, Class and its attributes have not been defined correctly.

Problems are with the syntax and not using some keywords. This has been Explained below.

Note that answer is provided only for the question asked which is on How to make the code to print the message.

Only The errors and Problems are covered with some suggestions .

1) Every class may have Constructor. Constructor is a function which create an object of the class and return the object.

Any parameters to set the values to the class variables can be written in init().

It can be defined as

Although constructors may not be used , but it is a good habit to use the constructors.

*The keyword 'self' has been explained in later parts below.

2) Also class objects/ instances are not iterable.

Your code gives the following error.

You must first create an object and then use the attribute or call the method in the class/ Instance.

Hence , change the code of Service function. Objects are created first as follows and functions are called.

3) And in the methods of class, you have a parameter self. The keyword 'self' refers to the object itself.

Hence if you run your code using just 'Observer' it raises an error saying ' Observer is not defined'.

Hence you must use 'self.Observer' which refers to the Observer attribute in the instance of class.Therefore edit the following method, and all other functions using 'self' keyword

if Observer = [ [Ob1] , [Ob2] ,[Ob2] ] , The code prints the above message three(3) times.

Suggestions and Additional Corrections or improvements.

* You might use( if it requires according to the question), is you should use Observer as a 2D list .

As in => Observer = [ [Email,SMS,Phone] ]

* Don't write Email, SMS, Phone. As it interprets them as variables. Instead use some values or strings. as

'Email', 0 , 1, 2.

* You could pass another parameter for the attach and detach function.

* In attach function, you may Append the list instead of values. append([email,sms,phone])

SCREENSHOTS:

CODE:

class ServiceNotifier:
#Subject responsible for notifying registered observer objects
   Observer= [[],[]]
   # def __init__(self):
   #    self.Observer = [[],[]]
  
   def attach(self):
#add new observer
       self.Observer.append(insertnewobserverhere)

   def dettach(self):
#remove an observer
       self.Observer.pop(insertnewobserverhere)

   def servicenotifier(self):
       for observers in self.Observer:
           print("Due to the forecast for tomorrow, all university and campus operations will be closed.")
  

##########################################################

def Service():
#Main code to execute
   alerts = ServiceNotifier()
   notify = alerts.servicenotifier()
   return notify

if __name__ == "__main__":
#Exectues the weather alert system
   Service()

*Thank You*

Add a comment
Know the answer?
Add Answer to:
How do I make my code print out the text in the ServiceNotifier class? Python Code:...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • This is Python 2.7 I'm trying to make my output look like this: ['weather: (55, 75,...

    This is Python 2.7 I'm trying to make my output look like this: ['weather: (55, 75, 80)', 'windspeed: 10', 'humidity: (35, 40)'] This is what it looks like now ['weather: (55, 75, 80)'] ['windspeed: 10'] ['humidity: (35, 40)'] ________________________________________________________________________________________________________________________________ This is how my code looks: def weather_strings(dictionary): 1_list = [ ] for key in dictionary.keys(): the_keys = str(key) val = str(dictionary[key]) print 1_list + [the_keys + ': ' + val] def main(): """This function prints the above functions""" test_dict =...

  • Python question. How do i make this code work? im trying to print the value of...

    Python question. How do i make this code work? im trying to print the value of the nodes using the level order trasversal class Node: def __init__(self, x): self.val = x self.left = None self.right = None class BinarySearchTree: def insertNode(self, value): self.root = self._insert(self.root, value)    def levelOrderTraversal(self, root): if root is None: return [] result, current = [], [root] while current: next_level, vals = [], [] for node in current: vals.append(node.val) if node.left: next_level.append(node.left) if node.right: next_level.append(node.right) current...

  • Write a program that does the following in Python Code: Write a new Class called Famous_Day_Born which is a subclass of Famous_Person. Add a method to calculate the day of the week the person was born...

    Write a program that does the following in Python Code: Write a new Class called Famous_Day_Born which is a subclass of Famous_Person. Add a method to calculate the day of the week the person was born and print out all of the corresponding information using the overridden print method. Use the following code below as a starting point. ////////////////////////////////////////////////////// from datetime import datetime class Famous_Person(object): def __init__(self, last, first, month,day, year): self.last = last self.first = first self.month = month...

  • Use of search structures! how can i make this program in python? Learning Objectives: You should...

    Use of search structures! how can i make this program in python? Learning Objectives: You should consider and program an example of using search structures where you will evaluate search trees against hash tables. Given the three text files under containing the following: - A list of students (classes Student in the distributed code) - A list of marks obtained by the students (classes Exam results in the distributed code) - A list of topics (classes Subject in the distributed...

  • Must be in Python 3 exercise_2.py # Define the Student class class Student():    # Ini...

    Must be in Python 3 exercise_2.py # Define the Student class class Student():    # Initialize the object properties def __init__(self, id, name, mark): # TODO # Print the object as an string def __str__(self): return ' - {}, {}, {}'.format(self.id, self.name, self.mark) # Check if the mark of the input student is greater than the student object # The output is either True or False def is_greater_than(self, another_student): # TODO # Sort the student_list # The output is the sorted...

  • I am currently facing a problem with my python program which i have pasted below where...

    I am currently facing a problem with my python program which i have pasted below where i have to design and implement python classes and record zoo database and takes user input as query. the error i am recieving says that in line 61 list index is out of range. kindly someone help me with it as soon as possible. Below is the program kindly check and correct it. Thanks! class Animal: def __init__(self, name, types, species, mass): self.name=name self.type=types...

  • I am currently facing a problem with my python program which i have pasted below where i have to design and implement python classes and record zoo database and takes user input as query. the error i...

    I am currently facing a problem with my python program which i have pasted below where i have to design and implement python classes and record zoo database and takes user input as query. the error i am recieving says that in line 61 list index is out of range. kindly someone help me with it as soon as possible. Below is the program kindly check and correct it. Thanks! class Animal: def __init__(self, name, types, species, mass): self.name=name self.type=types...

  • Hi, can someone offer input on how to address these 4 remain parts the zybook python...

    Hi, can someone offer input on how to address these 4 remain parts the zybook python questions?   4: Tests that get_num_items_in_cart() returns 6 (ShoppingCart) Your output ADD ITEM TO CART Enter the item name: Traceback (most recent call last): File "zyLabsUnitTestRunner.py", line 10, in <module> passed = test_passed(test_passed_output_file) File "/home/runner/local/submission/unit_test_student_code/zyLabsUnitTest.py", line 8, in test_passed cart.add_item(item1) File "/home/runner/local/submission/unit_test_student_code/main.py", line 30, in add_item item_name = str(input('Enter the item name:\n')) EOFError: EOF when reading a line 5: Test that get_cost_of_cart() returns 10 (ShoppingCart)...

  • I am having trouble with my Python code in this dictionary and pickle program. Here is...

    I am having trouble with my Python code in this dictionary and pickle program. Here is my code but it is not running as i am receiving synthax error on the second line. class Student: def__init__(self,id,name,midterm,final): self.id=id self.name=name self.midterm=midterm self.final=final def calculate_grade(self): self.avg=(self.midterm+self.final)/2 if self.avg>=60 and self.avg<=80: self.g='A' elif self.avg>80 and self.avg<=100: self.g='A+' elif self.avg<60 and self.avg>=40: self.g='B' else: self.g='C' def getdata(self): return self.id,self.name.self.midterm,self.final,self.g CIT101 = {} CIT101["123"] = Student("123", "smith, john", 78, 86) CIT101["124"] = Student("124", "tom, alter", 50,...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT