"AttributeError: 'list' object has no attribute 'SMSMessage'" - python

I have tried many ways but can't seem to get the length of my list through the method in my class my code:
SMSStore = []
unreadMessage = []
class SMSMessage(object):
def __init__(self, hasBeenRead, messageText, fromNumber):
self.hasBeenRead = hasBeenRead
self.messageText = messageText
self.fromNumber = fromNumber
hasBeenRead = False
def markAsRead(self, hasBeenRead):
hasBeenRead = True
def add_sms(self):
newMessage = (self.hasBeenRead, self.messageText, self.fromNumber)
return SMSStore.append(newMessage)
def get_count():
return len(SMSStore)
def get_message(self, i):
hasBeenRead = True
return SMSStore[i][1]
def get_unread_messages(i):
for i in SMSStore:
if SMSStore[i][0] == False:
unreadMessage.append(SMSStore[i])
print unreadMessage
def remove(self, i):
return SMSStore.remove(i)
This is how a message in the list would ideally look like:
#sample = SMSMessage(False, "Hello friend!", 0742017560)
And here is how the class is used
userChoice = ""
while userChoice != "quit":
userChoice = raw_input("What would you like to do - read/send/quit?")
if userChoice == "read":
print len(SMSStore)#this way i can get the length of the list anyway without using get_count
SMSStore(get_count()
unreadChoice = raw_input("Would you like to retrieve all unread messages or one of your own choice? - all unread/custom ")
if unreadChoice == "custom":
i = int(raw_input("Please enter which message number you want to read: "))
print get_message(i) #I dont understand how i works and how to get it working with the object definition
elif userChoice == "send":
messageText = raw_input("Please type in your message: ")
fromNumber = raw_input("Please type in the number it was sent from ")
newObject = SMSMessage(False, messageText, fromNumber)
newObject.add_sms()
print SMSStore
elif userChoice == "quit":
print "Goodbye"
else:
print "Oops - incorrect input"
I can just use len(SMSStore) but I want to be able to use the method inside the class to get it. Can point out any mistakes?
This was the question asked:
Open the file called​  sms.py​
Create a class definition for an SMSMessage which has three variables:
hasBeenRead, messageText, and fromNumber. 
The constructor should initialise the sender’s number. 
The constructor should also initialise hasBeenRead  to false
Create a method in this class called MarkAsRead which should change hasBeenRead to true.
Create a list called SMSStore to be used as the inbox.
Then create the following methods:
add_sms - which takes in the text and number from the received sms to
make a new SMSMessage object. 
get_count - returns the number of messages in the store.
get_message - returns the text of a message in the list.Forthis, allow the
user to input an index i.e. GetMessage(i) returns the message
stored at position i in the list. Once this has been done,
hasBeenRead should now be true. 
get_unread_messages - should return a list of all the messages which
haven’t been read. 
remove - removes a message in the SMSStore. 
Now that you have these set up, let’s get everything working! 

in your SMSMessage class
def get_count(self, *args):
return len(SMSStore)
in your script
# create instance
sms_msg = SMSMessage() # init arg needed
print sms_msg.get_count()
SMSStore is a global variable, you could remove get_count from SMSMessage scope
SMSStore = []
unreadMessage = []
class SMSMessage(object):
...functions...
def get_count(*args):
return len(SMSStore)
and call it regularly OR
ls = range(20)
class A(object):
# declare default value for your arguments
def __init__(self, hasBeenRead = False, messageText = "", fromNumber=0):
self.a = a
self.b = b
#using classmethod
#classmethod
def get_count(cls, *args):
return len(ls)
print A.get_count()

Related

TypeError 'type' object is not iterable

i use make_id to make id think but i got error: TypeError 'type' object is not iterable
i dont no why i got this error,can any person help me?
i am Chinese(Taiwan)
my code:
from msilib import make_id
from tkinter import simpledialog,Tk
def number():
win = make_id('')
def winner_number():
numberd = 'c4'
def get_task():
task=simpledialog.askstring("id製造器",'你要製造id嗎?')
return task
def get_message():
message=simpledialog.askstring('你的id是:',number,'中獎號碼:',winner_number)
return message
screen = Tk()
while True:
task=get_task()
if task == "要":
massage= get_message
number = make_id
if number(str) in winner_number():
print('你的運氣超好!!')
elif task=='cancel':
print('你失敗了!!')
else:
break
the code is have multiple errors but let me intrudes few of them
1 how functions values work in python
def function(values)
print(values)
function(10)
# 2nd way
def functions(values)
return values
a = function(10)
print(function(10))
# will give same result
so basically you are trying to do is just run stuff in function
def numebr():
win = make_id('')
def winner_number():
numberd = 'c4'
but you are comparing two function..
instade you could do
def number():
return make_id('')
def winner_number():
return 'c4'
if number() == winner_number():
print('you win')

Incomprehensible input behavior

There was a problem entering the fields of class. At the time of calling the add_well function, the default class fields specified in init function are displayed in the console. I don't understand why this behavior occurs and how to get rid of it. Can you help me?
def InputConsole(self, param):
return input(param)
#class of well
class well:
def __init__(self):
self.code_name = ''
self.depth = 0
self.pressure = 0
self.work = False
def input_properties(self):
print("-------- ADD WELL --------")
print('Code name: ')
self.code_name = InputConsole(self, self.code_name)
print('Depth: ')
self.depth = InputConsole(self, self.depth)
print('Pressure: ')
self.pressure = InputConsole(self, self.pressure)
print('Work: ')
self.work = InputConsole(self, self.work)
#class of field, container class
class field():
def __init__(self):
self.field = dict()
self.id_max = 0
def add_well(self):
wl = well()
wl.input_properties()
self.field[self.id_max] = wl
self.id_max += 1
print('Well was added\n\n')
def print_console(self):
print(self.field)
if self.id_max != 0 :
print("-------- INFO ABOUT FIELD --------")
for i in range(self.id_max):
self.field[i].print_properties()
print('')
else:
print('List is empty\n\n')
def main():
field = field()
field.add_well()
main()
Calling input() with a parameter uses the parameter as a prompt. Change the calls of InputConsole(self, self.code_name) to InputConsole(self, “Enter code name: “) and so on.
In addition, there’s really no reason you should be making an InputConsole function. You should also not be using self as a parameter for some of these methods, because your InputConsole, add_well, and print_console functions are not members of a class.

I am looking to create instances of a class from user input

I Have this class:
class Bowler:
def __init__(self, name, score):
self.name = name
self.score = score
def nameScore(self):
return '{} {}'.format(self.name, self.score)
I need to get user input until a blank line is entered. Then use the data I got to create instances of a class. I was thinking something like:
def getData():
name, score = input("Please enter your credentails (Name score): ").split()
B1 = Bowler(name, score)
print(B1.nameScore())
But then I would somehow have to loop it until I get a blank user input. Also I would somehow have to create B2 B3 B4 etc in the loop.
Sorry I am still really new to programming, maybe I am looking at this from the wrong angle.
What you're looking for are Python Lists. With these you will be able to keep track of your newly created items while running the loop. To create a list we simply defined it like so:
our_bowlers = []
Now we need to alter our getData function to return either None or a new Bowler:
def getData():
# Get the input
our_input = input("Please enter your credentails (Name score): ").split()
# Check if it is empty
if our_input == '':
return None
# Otherwise, we split our data and create the Bowler
name, score = our_input.split()
return Bowler(name, score)
and then we can run a loop, check for a new Bowler and if we didn't get anything, we can print all the Bowlers we created:
# Get the first line and try create a Bowler
bowler = getData()
# We loop until we don't have a valid Bowler
while bowler is not None:
# Add the Bowler to our list and then try get the next one
our_bowlers.append(bowler)
bowler = getData()
# Print out all the collected Bowlers
for b in our_bowlers:
print(b.nameScore())
This is my code to do what you want:
class Bowler:
def __init__(self, name, score):
self.name = name
self.score = score
def nameScore(self):
return '{} {}'.format(self.name, self.score)
def getData():
try:
line = input("Please enter your credentails (Name score): ")
except SyntaxError as e:
return None
name, score = line.split()
score = int(score)
B = Bowler(name, score)
print(B.nameScore())
return B
if __name__ == '__main__':
bowlers = list()
while True:
B = getData()
if B == None:
break
bowlers.append(B)
for B in bowlers:
print(B.nameScore())
In addition, I recommend you to modify your input for it's inconvenient now

python accessing another function variable error

I am trying to get input from one function and dispaying it in another function but i could not get the expected result
class Base(object):
def user_selection(self):
self.usr_input = input("Enter any choice")
user_input = self.usr_input
return user_input
def switch_selection(user_input):
print user_input
b = Base()
b.user_selection()
b.switch_selection()
When i execute this program i get
Enter any choice1
<__main__.Base object at 0x7fd622f1d850>
I should get the value which i entered but i get
<__main__.Base object at 0x7fd622f1d850>
How could i get the value which i entered?
def switch_selection(user_input):
print user_input
..
b.switch_selection()
You may notice that you're not passing any argument into switch_selection when calling it, yet you're expecting to receive one argument. That's something of a cognitive disconnect there. You happen to actually receive an argument though, which is b. An object method in Python receives its object instance as its first parameter. The argument you're receiving is not user_input, it's self. That's what you're printing, that's the output you're seeing.
Two possibilities to fix this:
class Base(object):
def user_selection(self):
self.user_input = input("Enter any choice")
def switch_selection(self):
print self.user_input
or:
class Base(object):
def user_selection(self):
return input("Enter any choice")
def switch_selection(self, user_input):
print user_input
b = Base()
input = b.user_selection()
b.switch_selection(input)
Try this Code Working perfect for me,
class Base(object):
def user_selection(self):
self.usr_input = input("Enter any choice")
user_input = self.usr_input
return user_input
def switch_selection(self,user_input):
print user_input
b = Base()
g=b.user_selection()
b.switch_selection(g)

Returning values from callback(s) in Python

I am currently looking at trying to use a callback in Python.
What I would like to do is return a value from the callback and then use this return value for conditional processing. So for example if the user enters "Y" I would like to print something to the console.
As I am new to Python the code below is as close as I can get currently but:
a) I am not sure if it is the Pythonic way of doing it
b) the correct way of doing it?
class Observable:
def subscribe(self,callback):
self.callback = callback
def fire(self):
self.callback()
class CallBackStuff:
def doCallback(self):
userInput = raw_input("Please enter Y or N?")
return userInput
if __name__ == '__main__':
s = CallBackStuff()
o = Observable()
o.subscribe(s.doCallback)
t = o.fire()
print t
The easiest way I can think of to do this in your code is to just store the input as
a variable in the CallBackStuff object. Then after you've called the call-back function, you can just access the input data from the CallBackStuff instance. Example below.
class Observable:
def subscribe(self,callback):
self.callback = callback
def fire(self):
self.callback()
class CallBackStuff:
storedInput = None # Class member to store the input
def doCallback(self):
self.storedInput = raw_input("Please enter Y or N?")
if __name__ == '__main__':
s = CallBackStuff()
o = Observable()
o.subscribe(s.doCallback)
o.fire()
print s.storedInput # Print stored input from call-back object
class Observable(object):
def __call__(self, fun):
return fun()
class Callback(object):
def docallback(self):
inp = raw_input()
return inp
if __name__ == "__main__":
print Observable()(Callback().docallback)

Categories

Resources