How to create and print the contents of a class? - python

I am creating a class structure in python for a city, that stores the name, country, population and language for a city, all of which are input by the user. The information shall then be printed.
I think that I may be successful in storing the information within the class structure (although this may be wrong as well), but I am unsuccessful in printing the information. Currently, I am receiving the error that int object is not subscriptable.
class User():
def _init_(self, username, password, email, numOfLogins):
User.username = username
User.password = password
User.email = email
User.numOfLogins = numOfLogins
#User Record Array Creation
def createUserArray(num , User):
UserArray = []
for x in range(num):
UserArray.append(User)
return UserArray
#User Record Array Population
def populateUserArray(num, UserArray):
for x in range(len(userArray)):
UserArray[x].username = str(input("Enter username."))
UserArray[x].password = str(input("Enter password."))
UserArray[x].email = str(input("Enter email address."))
UserArray[x].numOfLogins = int(input("Enter number of logins."))
return UserArray
#User Record Array Display
def displayUserArray(UserArray, num):
for x in range(len(userArray)):
print(UserArray[x].username, UserArray[x].password, UserArray[x].email, str(UserArray[x].numOfLogins))
#Top Level Program
numOfUsers = 3
userArray = createUserArray(numOfUsers, User)
userArray = populateUserArray(numOfUsers, userArray)
displayUserArray(numOfUsers, userArray)
The contents of the class should all be displayed at the end of the program, but at the minute my program crashes due to the error - int object is not subscriptable.

you can always implement the method : __str__(self) of an object , and then when you just print it with :
your_obj = User(...)
print your_obj
your __str__(self) will be called and you can return from it whatever you want to print.
for example:
def __self__(self):
return `this class has the following attributes: %s %s %s %s` % (self.username,self.password,self.email ,self.numOfLogins )
and this what will get print, i think it is more efficient and well coded to work like that and not creating a function that print each class attribute separately.

The cause of your error is quite simple and obvious: you defined the function as displayUserArray(UserArray, num) but call it with displayUserArray(numOfUsers, userArray) - IOW you pass the arguments in the wrong order.
This being said, almost all your code is wrong, you obviously don't get the difference between a class and instance and how to use a class to create instances. I strongly suggest you read at least the official tutorial, and check a couple other tutorial and/or example code on the topic of classes and instances.

Related

Input from user to print out a certain instance variable in python

I have created a class with programs:
class Program:
def __init__(self,channel,start, end, name, viewers, percentage):
self.channel = channel
self.start = start
self.end = end
self.name = name
self.viewers = viewers
Channel 1, start:16.00 end:17.45 viewers: 100 name: Matinee:The kiss on the cross
Channel 1, start:17.45 end:17.50 viewers: 45 name: The stock market today
Channel 2, start:16.45 end:17.50 viewers: 30 name: News
Channel 4, start:17.25 end:17.50 viewers: 10 name: Home building
Channel 5, start:15.45 end:16.50 viewers: 28 name: Reality
I also have created a nested list with the programs:
[[1,16:00, 17,45, 100, 'Matinee: The kiss on the cross'],[1,17:45, 17,50, 45,'The stock market today'],[2,16:45, 17,50, 30,'News'], [4,17:25, 17,50, 10,'Home building'],[5,15:45, 16,50, 28,'Reality']
Now we want the user to be able to write the name of a program:
News
The result should be:
News 19.45-17.50 has 30 viewers
I thought about how you could incorporate a method to avoid the program from crashing if the input is invalid/ not an instance variable
I have tried this:
Check_input():
print('Enter the name of the desired program:')
while True: #Continue asking for valid input.
try:
name = input('>')
if name == #is an instance?
return name
else:
print('Enter a program that is included in the schedule:') #input out of range
except ValueError:
print('Write a word!') #Word or letter as input
print('Try again')
I wonder if I should separate all the program-names from the nested list and check if the user enters a name in the list as input? (Maybe by creating a for-loop to iterate over?)
I also have a question regarding how to print out the selected program when the user enters the correct name? I understand how to rearrange them into the correct order to create the sentence. However, I don't know how to access the correct program in the "memory"
Do you have any suggestions how to combat the problem?
All help is much appreciated!
I wonder if I should separate all the program-names from the nested list and check if the user enters a name in the list as input? (Maybe by creating a for-loop to iterate over?)
Well if all your programs have a unique name then the easiest approach would probably be to store them in a dictionary instead of a nested list like:
programs = {
"News": Program("2", "16:45", "17:50", "News", "30", "60"),
"Reality": <Initialize Program class object for this program>,
...
}
Then you could just use the get dictionary method (it allows you to return a specific value if the key does not exist) to see if the asked program exists:
name = input('>')
program = programs.get(name, None)
if program:
print(program)
else:
# raise an exception or handle however you prefer
And if your programs don't have a unique name then you will have to iterate over the list. In which case I would probably return a list of all existing objects that have that name. A for loop would work just fine, but I would switch the nested list with a list of Program objects since you already have the class.
I also have a question regarding how to print out the selected program when the user enters the correct name? I understand how to rearrange them into the correct order to create the sentence. However, I don't know how to access the correct program in the "memory" Do you have any suggestions how to combat the problem.
I would say that the most elegant solution is to override the __str__ method of your Program class so that you can just call print(program) and write out the right output. For example:
class Program:
def __init__(self,channel,start, end, name, viewers, percentage):
self.channel = channel
self.start = start
self.end = end
self.name = name
self.viewers = viewers
def __str__(self):
return self.name + " " + self.start + "-" + self.end + " has " + self.viewers + " viewers"
should print out
News 19.45-17.50 has 30 viewers
when you call it like:
program = programs.get(name, None)
if program:
print(program)

Using Class to Call a User Input

I'm trying to use a class to store a user input but seem to be running into some issues. I would normally just use input() but the class I'm taking is asking us to build a class that represents an object of interest. Below is the code that I've developed so far but I feel like I'm making a class for the sake of making a class. Am I missing something here?
import requests
class Requirement:
def __init__(self, address):
self.address = input("enter address here")
return address
address = input('Enter Address')
loc = Nominatim(user_agent="GetLoc")
getLoc = loc.geocode({address})
# printing address
print(getLoc.address)
# printing latitude and longitude
print("Latitude = ", getLoc.latitude, "\n")
print("Longitude = ", getLoc.longitude)```

python classes dynamic object instantiation/creation

I want to create some users just to populate my database, so using decorators I created a method inside a class for it. I returned the results into a list and used the information without a problem. But after a while I thought that once I was working with classes wouldn't be dumb to use lists? I feel that I am kind of moving backwards since, at least in my understanding, it might be possible to access those values directly.. But the truth is I struggled on attempting to instantiate dynamically and access those instances. So, how could I do that properly? Here is the code I wrote in the first attempt:
class User:
def __init__(self, user_name, password, email, i=0):
self.user_name = user_name
self.password = password
self.email = email
#classmethod
def from_generate(cls, amount):
user_name = 'user' + str(amount)
password = 'password000.' + str(amount)
email = 'user' + str(amount) + "#whatever.com"
return cls(user_name, password, email)
in another file:
def user_generator(user_qty=0):
user_list = []
for i in range(1, user_qty + 1):
# call the class method to generate users
instance = User.from_generate(i)
user_list.append(instance)
return(user_list)
users = user_generator(5)
if __name__ == "__user_generator__":
user_generator()

Calling a function from a class in main

I seem to be making a stupid mistake that I cant find. Im simply trying to call my functions from my record class and having an invalid syntax error despite looking at sample code and trying to emulate the syntax.
Ive tried following tutorials and calling the function in every which way so the problem may not be in the calling of the function but something else I feel.
class definitions
class record:
def __init__(self,telephone,lastname,firstname):
self.telephone = telephone
self.lastname = lastname
self.firstname = firstname
def addrecord(self,x,y,z):
x = input('Enter telephone number')
y = input('Enter lastname')
z = input('Enter firstname')
phonebook.append(record(x,y,z))
return
def deleterecord(self,x):
phonebook[x-1].pop
return
Main
phonebook = record[]
addrecord(515,'fin','matt')
print(phonebook[0].firstname)
deleterecord(1)
print(phonebook[0].firstname)
If all this works I expect the output to be
"matt"
"null"
There are a number of problems with your code:
you are defining phonebook otuside of the class
in deleterecord you should call phonebook.pop(x).
there should be two classes that handle the phonebook and records, and the record could be modeled using a namedtuple.
there are syntax errors like calling record[] which is not valid Python.
Alternative implementation:
from collections import namedtuple
PhoneRecord = namedtuple("PhoneRecord", ['firstname', 'lastname', 'telephone'])
class PhoneBook:
def __init__(self):
self._phonebook = []
def addrecord(self, record):
self._phonebook.append(record)
return self._phonebook.index(record)
def deleterecord(self, i):
self._phonebook.pop(i)
phonebook = PhoneBook()
record_index = phonebook.addrecord(PhoneRecord(firstname="matt", lastname="snow", telephone="25512521"))
print(phonebook._phonebook)
phonebook.deleterecord(record_index)
print(phonebook._phonebook)
which will yield in the console:
[PhoneRecord(firstname='matt', lastname='snow', telephone='25512521')]
[]
The simplified version of your question is, given code
records = []
records.append("matt")
print(records[0])
del records[0]
print(records[0])
why don't I get the following output
"matt"
None
Instead, you get an IndexError exception.
The reason is that you are accessing an element beyond the size of the list, and Python handles this by raising an exception rather than returning None.

Creating a list within an object (book/patron waitlist)

I have a homework assignment to create a "library" with a patron class and book class. This library should allow people to check out up to 3 books, and add a book to a patron's waitlist if the book is already checked out. Upon the books return, it should be automatically checked out to the first person on the waitlist. I can't seem to get the list to work. Here's my code:
class Patron(object):
def __init__(self,name,booksOut=0):
self._name=name
self._booksOut=booksOut
def getBooksOut(self):
return self._booksOut
def __str__(self):
result="Name: "+self._name+"\n"
result+="Books Out: "+str(self._booksOut)+"\n"
return result
class Book(object):
def __init__(self,title,author,owner=None):
self._title=title
self._author=author
self._owner=owner
self._queue=[] #Here is the empty list I'm using... but it doesn't seem to be working.
def setOwner(self,owner):
self._owner=owner
def getOwner(self):
return self._owner
def borrowMe(self, patron):
if self._owner != None:
return "This book is not available. You've been added to the queue.\n"
self._queue.append(patron)
print(str(self._queue)) #I can't even get the list to print, so I'm feeling like I didn't create it correctly
else:
if patron.getBooksOut()>=3:
return "You have too many books checked out!"
else:
self.setOwner(patron)
patron._booksOut+=1
return "You have successfully checked this book out."
def returnMe(self):
if len(self._queue)==0:
self.setOwner(None)
return "Your book has been returned."
else:
return "Your book has been given to: "+str(self._queue[0])
self.borrowMe(self._queue[0]) #Here is where I'm trying to automatically borrow the book to the first person in the waitlist
def __str__(self):
result="Title: "+self._title+"\n"
result+="Author: "+self._author+"\n"
if self._owner != None:
result+="Owner: "+str(self.getOwner())
else:
result+="Owner: None"
return result
def main():
"""Tests the Patron and Book classes."""
p1 = Patron("Ken")
p2 = Patron("Martin")
b1 = Book("Atonement", "McEwan")
b2 = Book("The March", "Doctorow")
b3 = Book("Beach Music", "Conroy")
b4 = Book("Thirteen Moons", "Frazier")
print(b1.borrowMe(p1))
print(b2.borrowMe(p1))
print(b3.borrowMe(p1))
print(b1.borrowMe(p2))
print(b4.borrowMe(p1))
print(p1)
print(b1)
print(b4)
print(b1.returnMe())
print(b2.returnMe())
print(b1)
print(b2)
I've #commented the parts containing the list creation (in the init for the book class) and where I tried to print the list to do some error checking (in the borrowMe method) and also where I am trying to automatically borrow the book to the first person on the waitlist/queue (in the returnMe method).
Any insight is appreciated.
if self._owner != None:
return "This book is not available. You've been added to the queue.\n"
self._queue.append(patron)
print(str(self._queue))
You are printing after return. Nothing will be executed after return. Change it to print. Also in Patron class, change __str__ to __repr__. Otherwise it will print a list of memory addresses. In addition, print(str(self._queue)) is redundant, you could print the list directly.

Categories