how to fix this error? python <__main__.Employee at 0x7f2358d89910> None - python

here is the output
Enter your ID: 1234
Enter your NAME: Name
Enter your AGE: 20
Enter your Birthdate: 12
EMPLOYMENT STATUS:
Enter 1 if you are employed:
Enter 2 if unemployed:
1
Enter 1 if the employment is permanent:
Enter 2 if the employment a job-order:
2
<__main__.Employee at 0x7f2358d89910>
None
the NONE keeps appearing, I want to get the information which is set by the user in display(employee_object) but I don't know hw
class Employee(object):
# initialize values
def __init__(self):
self.id = ""
self.name = ""
self.age = ""
self.birthdate = ""
self.status = ""
# setter methode for setting values to the class properties
def set_id(self, id):
self.id = id
def set_name(self, name):
self.name = name
def set_age(self, age):
self.age = age
def set_birthdate(self, birthdate):
self.birthdate = birthdate
def set_status(self, status):
self.status = status
# getter methode for getting values of the class properties
def get_id(self):
return self.id
def get_name(self):
return self.name
def get_age(self):
return self.age
def get_birthdate(self):
return self.birthdate
def get_status(self):
return self.status
# methode which takes object as an argument and display its properties
def display(employee_object):
print("ID : ", employee_object.get_id())
print("Name : ", employee_object.get_name())
print("Age : ", employee_object.get_age())
print("Birthdate : ", employee_object.get_birthdate())
print("Status : ", employee_object.get_status())
# calls class Employee
# Main methode of the program
if __name__ == "__main__":
employee_List = []
emp_1 = Employee()
# appending objects to the list
employee_List.append(emp_1)
# Initializing each objects of the list
for employee in employee_List:
emp_id = input("Enter your ID: ")
employee.set_id(emp_id)
emp_name = input("Enter your NAME: ")
employee.set_name(emp_name)
emp_age = input("Enter your AGE: ")
employee.set_age(emp_age)
emp_birthdate = input("Enter your Birthdate: ")
employee.set_birthdate(emp_birthdate)
emp_stat1 = input("EMPLOYMENT STATUS: \nEnter 1 if you are employed: \nEnter 2 if unemployed: \n")
if emp_stat1 == '1':
emp_stat2 = input("Enter 1 if the employment is permanent: \nEnter 2 if the employment a job-order: \n")
if emp_stat2 == '1':
employee.set_status = "PERMANENT"
elif emp_stat2 == '2':
employee.set_status = "JOB ORDER"
elif emp_stat1 == '2':
emp_stat2 = input("Enter 1 if you are a freelancer: \nEnter 2 if you are seeking a job: \n ")
if emp_stat2 == '1':
employee.set_status = "FREELANCER"
elif emp_stat2 == '2':
employee.set_status = "JOB SEEKER"
# Displaying each objects of the list
for employee_object in employee_List:
print(display(employee_object))

When using print, python will call the str method of your class, therefore if you want to print readable information you can do it by using
print(employee_object)
and inserting the str method to your class, which could be something like:
def __str__(self):
return f'The employee {self.name} is {self.status}'

As no return is specified in display method, the default is None , see How to prevent Python function from returning None
Your display method shows things, you don't expected it to return anything, so call it like
# Displaying each objects of the list
for employee_object in employee_List:
display(employee_object)
Then some python-coding specifics
What's the pythonic way to use getters and setters? using #property
# If you defined a self._name attribut
#property
def name(self):
return self._name
#name.setter
def name(self, name):
self._name = name
# GET use : employee.name
# SET use : employee.name = emp_name
Use a constructor with parameters, that nicer
class Employee(object):
def __init__(self, emp_id, name, age, birthdate, status):
self._id = emp_id
self._name = name
self.age = age
self.birthdate = birthdate
self.status = status
Don't use a outer method display, there is a built-in way with __str__ (or __repr__) see Difference between __str__ and __repr__, add it to the Employee class and it'll be use then you do print(emp) where emp is an Employee instance
def __str__(self):
return "\n".join((
f"ID: {self.id}",
f"Name: {self.name}",
f"Age: {self.age}",
f"Birthdate: {self.birthdate}",
f"Status: {self.status}",
))
Then the principe you used of create a list / add one instance / iterate on the list to populate the instance isn't a good idea, because you have a fixed amount of employee which isn't dynamically given.
I'd suggest to use a while loop that will stops when you enter stop at the ID input
employee_List = []
while True:
emp_id = input("Enter your ID: ('stop' to quit)")
if emp_id == "stop":
break
emp_name = input("Enter your NAME: ")
emp_age = input("Enter your AGE: ")
emp_birthdate = input("Enter your Birthdate: ")
emp_stat1 = input("EMPLOYMENT STATUS: \nEnter 1 if you are employed: \nEnter 2 if unemployed: \n")
if emp_stat1 == '1':
emp_stat2 = input("Enter 1 if the employment is permanent: \nEnter 2 if the employment a job-order: \n")
if emp_stat2 == '1':
emp_status = "PERMANENT"
elif emp_stat2 == '2':
emp_status = "JOB ORDER"
elif emp_stat1 == '2':
emp_stat2 = input("Enter 1 if you are a freelancer: \nEnter 2 if you are seeking a job: \n ")
if emp_stat2 == '1':
emp_status = "FREELANCER"
elif emp_stat2 == '2':
emp_status = "JOB SEEKER"
emp = Employee(emp_id, emp_name, emp_age, emp_birthdate, emp_status)
employee_List.append(emp)
for employee_object in employee_List:
print(employee_object, "\n")
FULL CODE

Related

How to do I connect my two modules within my Bank and Account classes?

I'm a newbie to python. I'm writing a banking program script. The Bank has a defined name and address. Where the Account has a defined, first name, last name, and balance.
I'm testing the code by trying to transfer money from one account to another. But I'm getting an error after entering accounts. Where did I go wrong?
from account import Account
class Bank:
name = ''
address = ''
all_accounts = {}
def __init__(self, name, address):
self.name = name
self.name = address
def create_account(self, firstname, lastname, balance):
accounts = Account(firstname, lastname, balance)
self.all_accounts[Account] = accounts
def show_accounts(self, show_history=False):
for account in self.all_accounts.items():
print(account)
def transfer(self, ac1, ac2, balance):
if self.all_accounts[ac1].withdraw(balance):
self.all_accounts[ac2].deposit(balance)
def get_account(self, account_customers):
return self.all_accounts[account_customers]
class Account:
# firstname = ''
# lastname = ''
# balance = ''
def __init__(self, firstname, lastname, balance=0):
self.firstname = firstname
self.lastname = lastname
self.balance = balance
self.number_of_deposits = 0
self.number_of_withdraws = 0
self.history = []
def desc(self):
print("Name is: ", self.firstname, self.lastname)
print("Balance: ", self.balance)
return True
def deposit(self, value):
self.balance += value
self.history.append(value)
self.number_of_deposits += 1
return True
def withdraw(self, value):
if self.balance < value:
print(f'{self.firstname, self.lastname} not enough money')
return False
self.balance -= value
self.history.append(-value)
self.number_of_withdraws += 1
return True
def transfer(self):
answer = int(input("Enter amount of $ to transfer"))
if answer < 0:
print("Choose a value above $0")
else:
print("Your transfer was successful")
from account import Account
from bank import Bank
bank = Bank("Bank of Westeros", "1 Park Place, Westeros, GoT")
ac1 = bank.create_account("Carrot", "Top", 5000)
ac2 = bank.create_account("Dolly", "Parton", 10000)
To add an item to a list, use the .append method. What you have written in the last line of create_account doesn't make sense. Replace:
self.all_accounts[Account] = accounts
with this:
self.all_accounts.append(accounts)

Object Oriented Programming with python issue with the list?

Code is not printing the multiple elements that I add to it. Instead it is just printing out the recently added element. can anyone guide me on this?
class bikes:
def __init__(self,make,name,model):
self.make = make
self.name = name
self.model = model
self.all_bikes = []
def total_bikes(self):
self.counter = 0
dict_bikes = {"Make": self.make,
"Name": self.name,
"Model": self.model}
self.all_bikes.append({self.counter : dict_bikes})
self.counter = self.counter + 1
def show_all_bikes(self):
print(self.all_bikes)
class user(bikes):
def __init__(self):
self.user_make = make = input("Enter the Company name: ")
self.user_name = name = input("Enter the Bike name: ")
self.user_model = model = input("Enter the Model name: ")
super().__init__(make,name,model)
bikes.total_bikes(self)
while True:
menu = input("Enter Add,View to Add a new bike and View all bikes: ")
if menu.upper() == "ADD":
add_bike = user()
elif menu.upper() == "VIEW":
add_bike.show_all_bikes()
else:
print("Invalid Command")
This construct
while True:
menu = input("Enter Add,View to Add a new bike and View all bikes: ")
if menu.upper() == "ADD":
add_bike = user()
elif menu.upper() == "VIEW":
add_bike.show_all_bikes()
else:
print("Invalid Command")
if ADD is choice then new instance of user class is created, which has empty all_bikes. You need to equip your class with seperate method for adding bike and __init__ and createdinstance of user class before entering while loop.

Python iterate through a list of class objects and extract a value

Hello I am having some trouble with trying to iterate through a list of classes in order to print out a particular value that thet instance of that class holds.My program compiles but it does not print any thing out, I have also tried having "player.player in playerlist" in the for loop but I also got the same result.Any help would be greatly appreciated.
My main function
class main:
if __name__ == '__main__':
while True:
print("Please Select An Option Below:")
print("1 - Create Player:")
print("2 - List Players:")
print("3 - Create Team:")
print("4 - Sell Player:")
print("5 - Buy Player:")
x = raw_input("Please select a option: \n")
playerList = []
if(x == '1'):
import Player
p1 = Player.player()
pname = raw_input("Please Enter A Player Name \n")
page = raw_input("Please Enter A Player Age \n")
pwage = raw_input("Please Enter A Player Wage \n")
pteam = raw_input("Please Enter A Player Team \n")
p1.pname = pname
p1.page = page
p1.pwage = pwage
p1.pteam = pteam
playerList.append(p1)
continue
if(x == '2'):
for p1 in playerList:
print(p1.pname)
continue
My player class
class player(object):
#property
def pname(self):
return self.pname
#pname.setter
def pname (self, value):
pass
#property
def page(self):
return self.page
#page.setter
def page (self, value):
pass
#property
def pwage(self):
return self.pwage
#pwage.setter
def pwage(self, value):
pass
#property
def pteam(self):
return self.pteam
#pteam.setter
def pteam(self, value):
pass
----update-----
class main:
if __name__ == '__main__':
while True:
print("Please Select An Option Below:")
print("1 - Create Player:")
print("2 - List Players:")
print("3 - Create Team:")
print("4 - Sell Player:")
print("5 - Buy Player:")
x = raw_input("Please select a option: \n")
playerList = []
if(x == '1'):
import Player
nplayer = Player.player()
nplayer.set_name(raw_input("test\n"))
playerList.append(nplayer)
continue
if(x == '2'):
for player in playerList:
print(player.get_name)
continue
class player(object):
__name = ""
#property
def get_name(self):
return self.__name
def set_name(self, name):
self.__name = name
When you write p1.pname = pnamethe setter is called. However, you don't do anything in the setter. So when the getter is called later, it doesn't have anything to return.
For getters and setters to work in python, you need to do something like this:
class player(object):
#property
def pname(self):
return self._pname
#pname.setter
def pname (self, value):
self._pname = value
Many thanks to those who helped it my problem was caused by not setting up the setter/getter properly as told above and me having my array in the display menu option causing it to send the instance of the class to another list.
class main:
if __name__ == '__main__':
playerList = []
while True:
print("Please Select An Option Below:")
print("1 - Create Player:")
print("2 - List Players:")
print("3 - Create Team:")
print("4 - Sell Player:")
print("5 - Buy Player:")
x = raw_input("Please select a option: \n")
if(x == '1'):
import Player
nplayer = Player.player()
nplayer.set_name(raw_input("Please Enter A Name\n"))
playerList.append(nplayer)
continue
if(x == '2'):
for nplayer in playerList:
print(nplayer.get_name)
continue
class player(object):
__name = ""
#property
def get_name(self):
return self.__name
def set_name(self, name):
self.__name = name

How do I fix: TypeError: object() takes no parameters?

Here's my program:
class member:
name = ""
phone = ""
number = 0
def init(self, name, phone, number):
self.name = name
self.phone = phone
self.number = number
def setName(self, name):
self.name = name
def setPhone(self, phone):
self.phone = phone
def setNumber(self, number):
self.number = number
def getName(self):
return self.name
def getPhone(self):
return self.phone
def getNumber(self):
return self.number
def displayData(self):
print("")
print("Name:", self.name)
print("Phone:", self.phone)
print("Jersey Number:", self.number)
def displayMenu():
print("")
print("==========Main Menu==========")
print("1. Display Team Roster.")
print("2. Add Member.")
print("3. Remove Member.")
print("4. Edit Member.")
print("5. Save Data.")
print("6. Load Data.")
print("9. Exit Program.")
print("")
return int(input("Selection> "))
def printMembers(memberList):
if len(memberList) == 0:
print("No Current Members in Memory.")
else:
for x in memberList.keys():
memberList[x].displayData()
def addMember(memberList):
newName = input("Enter new member's name: ")
newPhone = input("Contact phone number: ")
newNumber = int(input("Jersey number: "))
memberList[newName] = member(newName,newPhone,newNumber)
#An updated list is returned.
return memberList
def removeMember(memberList):
removeName = input("Enter member name to be Removed: ")
#First, check to see if the name given, already exists in the list.
if removeName in memberList:
#Use the del key to delete the entry at the given name.
del memberList[removeName]
else:
print("Member not found in list.")
#An updated list is returned.
return memberList
def editMember(memberList):
#get the name of the member to be edited.
oldName = input("Enter the name of the member yopu want to edit. ")
#See if name is already in the list, if yes, get the index of the.
#given name, accept the new one, and replace the name in the list.
#with the new name.
#An updated list is returned.
if oldName in memberList:
newName = input("Enter the member's new name: ")
newPhone = input("Contact phone number: ")
newNumber = int(input("Jersey number: "))
memberList[oldName] = member(newName, newPhone, newNumber)
return memberList
def saveData(memberList):
filename = input("File name to be saved: ")
print("Saving Data...")
outFile = open(filename, "wt")
for x in memberList.keys():
name = memberList[x].getName()
phone = memberList[x].getPhone()
number = str(memberList[x].getNumber())
outFile.write(name+","+phone+","+number+"\n")
print("Data saved.")
outFile.close()
def loadData():
memberList ={}
filename = input("Filename to Load: ")
inFile = open(filename, "rt")
print("Loading Data...")
while True:
#Read in a line of text from the text file.
inLine = inFile.readline()
#If the line is empty, stop loading data.
if not inLine:
break
inLine = inLine[:-1]
name, phone, number = inLine.split(",")
memberList[name] = member(name, phone, int(number))
print("Data Loaded Successfully")
inFile.close()
return memberList
print("Welcome to the Team Manager")
#Create an empty dictionary by changing tthe [] to {}
memberList = {}
#Get the first menu selection from the user and store it in a control value variable.
menuSelection = displayMenu()
#The main program loop will detect the correct entry from the user and call the appropriate.
#method from the user's selection.
while menuSelection != 9:
if menuSelection == 1:
printMembers(memberList)
elif menuSelection == 2:
memberList = addMember(memberList)
elif menuSelection == 3:
memberList = removeMember(memberList)
elif menuSelection == 4:
memberList = editMember(memberList)
elif menuSelection == 5:
memberList = saveData(memberList)
elif menuSelection == 6:
memberList = loadData()
menuSelection = displayMenu()
print ("Exiting Program...")
Here's my error:
C:\Users\Patrick\AppData\Local\Programs\Python\Python36-32\python.exe C:/Users/Patrick/PycharmProjects/Week_6_assignment.py/Week_6_assignment.py
Welcome to the Team Manager
==========Main Menu==========
1. Display Team Roster.
2. Add Member.
3. Remove Member.
4. Edit Member.
5. Save Data.
6. Load Data.
9. Exit Program.
Selection> 2
Enter new member's name: margie
Contact phone number: 3134562252
Jersey number: 88
Traceback (most recent call last):
File "C:/Users/Patrick/PycharmProjects/Week_6_assignment.py/Week_6_assignment.py", line 151, in <module>
memberList = addMember(memberList)
File "C:/Users/Patrick/PycharmProjects/Week_6_assignment.py/Week_6_assignment.py", line 74, in addMember
memberList[newName] = member(newName,newPhone,newNumber)
TypeError: object() takes no parameters
Process finished with exit code 1
Any suggestions?
You named your initializer method init; the correct name is __init__. The double underscores are how Python indicates names reserved for Python "special" use. By not using the correct name, the superclass (object's) __init__ was invoked, but it takes no arguments, so you get the error.
Sidenotes: You've got another error in saveData; the final print and close calls should almost certainly be dedented, so you write all the data, not just a single item.
In addition:
while True:
#Read in a line of text from the text file.
inLine = inFile.readline()
#If the line is empty, stop loading data.
if not inLine:
break
inLine = inLine[:-1]
name, phone, number = inLine.split(",")
memberList[name] = member(name, phone, int(number))
should almost certainly become (importing csv at the top of the file):
for name, phone, number in csv.reader(inFile):
memberList[name] = member(name, phone, int(number))
which handles newlines and splitting on commas for you, and doesn't involve the anti-pattern of an infinite loop calling .readline() over and over (even if this wasn't CSV, the correct way to iterate by line is for inLine in inFile:, which avoids the while, readline and if not inLine: break; for inLine in map(str.rstrip, inFile): avoids the need to explicitly slice off the trailing newline too).
You're missing __. Your
def init(self, name, phone, number):
self.name = name
self.phone = phone
self.number = number
has to be
def __init__(self, name, phone, number):
self.name = name
self.phone = phone
self.number = number

How to properly use __repr__ when two classes are involved

I am working on some Python code where I create a basic ATM. The issue I am having is I am not able to get the result that I want its printing "<'function Account.balance at 0x012CBC90>" Instead of the actual balance number. So far I have only tested using jsmith. Feel free to call out any other issues that may cause a problem later.
class Account:
def __init__(self,user,pin,balance):
self.user = user
self.pin = pin
self.balance = int(balance)
def get_user(self):
return self.user
def get_pin(self):
return self.pin
def balance(self):
return int(self.balance)
def setBalance(self,newBalance):
self.balance = newBalance
def __repr__(self):
return str(self.user) + " " + str(self.pin) + " " + str(self.balance)
class ATM:
def withdraw(self,Person,amount):
result = Person - amount
return result
def check(self,Person):
Person = Account.balance
return str(Person)
def transfer(self,id1,id2):
pass
def __str__(self):
return self
def main():
Chase = ATM()
Database = []
Teron_Russell = Account("trussell",1738,0)
Joe_Smith = Account("jsmith",1010,1350)
print(Teron_Russell)
Database.append(Teron_Russell)
Database.append(Joe_Smith)
print("Welcome to the ATM")
id = input("Please enter your user ID: ")
pin = input("Enter your pin: ")
chosen = ""
for i in Database:
print("Test1")
name = Account.get_user(i)
print(name)
checkPin = Account.get_pin(i)
print(checkPin)
if id == name and pin == checkPin:
chosen = i
choice = input("What would you like to do. (Type 'Check','Withdraw','Transfer': ")
if(choice == "Check" or "check"):
print(Chase.check(chosen))
# if(choice == "Withdraw" or "withdraw"):
# wAmount = eval(input("How much would you like to Withdraw: "))
# # Chase.withdraw(Account.balance,)
# elif(choice == "Check" or "check"):
# Chase.check()
# else:
# print("Invalid Choice!")
if __name__ == "__main__":
main()
You named a variable and a method the same name, so the interpreter is confused on which one to use. Change the name of either the method or variable balance and you won't have this problem. Additionally, this isn't java, and you shouldn't use classes for no reason. Since you aren't using any instance variables, it is pointless to have all of those methods inside that class.

Categories