AttributeError when calling instance method I defined - python

I coded this in python 3 and it is showing an attribute error.code is
as following:
import datetime
class MessageUser():
User_Details = []
Messages = []
base_message = """Hi {name}!
Thank you for the purchase on {date}.
We hope you are exicted about using it. Just as a
reminder the purcase total was ${total}.
Have a great time!
from Pritom_Mazhi
"""
def add_user(self, name, amount, email=None):
name = name[0].upper() + name[1:].lower() #Capitalizing the first letter of all names - formatted name
amount = "%.2f" %(amount) #formatted amount
detail = {
"name" : name,
"amount" : amount,
}
today = datetime.date.today()
date_text = '{tday.day}/{tday.month}/{tday.year}'.format(tday=today) #formatted date
detail["date"] = date_text
if email is not None:
detail["email"] = email
self.User_Details.append(detail)
def get_details(self):
return self.User_Details
def make_message(self):
if len(self.User_Details) > 0:
for detail in self.get_details(): #for detail in self.User_Details
name = detail["name"]
amount = detail["amount"]
date = detail["date"]
email = detail["email"]
message = self.base_message
formatted_message = message.format(
name = name,
total = amount,
date = date,
)
self.Messages.append(formatted_message)
return self.Messages
else:
return []
obj = MessageUser()
obj.add_user("Pritom", 123.32, email='hello#teamcfe.com')
obj.add_user("jon Snow", 94.23)
obj.add_user("Sean", 93.23)
obj.add_user("Emilee", 193.23)
obj.add_user("Marie", 13.23)
obj.get_details()
obj.make_message()
when i run it i get this error:
File "Class_StringFormat.py", line 57, in <module>
obj.get_details()
AttributeError: 'MessageUser' object has no attribute 'get_details'
i simply can't find what wrong i did there and so can't manage to fix it.

If your indentation is reproduced correctly in the question, get_details is defined inside add_user and is not visible from outside.
You should unindent the definition of get_details and make_message to be on the same level as add_user:
def add_user(self, name, amount, email=None):
# method body...
def get_details(self):
return self.User_Details
def make_message(self):
# method body

Related

How can I get data for a class object, taking input from user of which object he would like to view?

First i created a class named 'employed' which looks like this-
class employed:
def __init__(self,name, age, salary, role):
self.name = name ; self.age = age
self.salary = salary ; self.role = role
def givedata(self):
return(f"name : {self.name}\nage : {self.age}\nsalary : {self.salary}\nrole : {self.role}")
Then, i created two class objects for this class-
saksham = employed("Saksham", 13, 10000, "developer")
rohan = employed("Rohan", 15, 12000, "team leader")
Now i want to take input from the user of which object's data he like to view. How can i do that?
First, we defined a function which returns the user who matches the name
if the function returns none means there is no user that name otherwise it will return user.
Before that, I've added all users into list for convineince
saksham = employed("Saksham", 13, 10000, "developer")
rohan = employed("Rohan", 15, 12000, "team leader")
objects = []
objects.append(saksham)
objects.append(rohan)
def view_object(name):
for user in objects:
if user.name == name:
return user;
name = input("Hey User... Who do you want to view: "
user = view_object(name)
if user is None:
print("Sorry there is no user with this name")
else:
print(str(user))
There is no switch case in python but you can implement it as follows
define these functions in class
def get_name(self):
return self.name
def get_salary(self):
return self.salary
then use the following method
def numbers_to_months(argument):
switcher = {
1: object.get_salary(),
2: object.get_name(),
}
# Get the function from switcher dictionary
func = switcher.get(argument, lambda: "Invalid month")
# Execute the function
print get_salary()

Class object does not update empty list

I'm trying to solve this problem on my own. The problem asks to write a class for employee information, then ask user to input that information, and finally print the entered information.
I want to use two for loops, one for getting information and one for printing the information. Unfortunately, the printing for loop does not working.
class Employee:
def __init__(self, name, id_num, department, job):
self.__name = name
self.__id_num = id_num
self.__department = department
self.__job = job
# setters
def set_name(self,name):
self.__name = name
def set_id(self,id_num):
self.__id_num = id_num
def set_department(self,department):
self.__department = department
def set_job(self,job):
self.__job = job
# getters
def get_name(self):
return self.__name
def get_id(self):
return self.__id_num
def get_department(self):
return self.__department
def get_job(self):
return self.__job
def main():
employee_list = []
for i in range(2):
name = input('What is the name of the employee? ')
id_num = float(input('What is the ID number of the employee? '))
department = input('What is the department where the employee works? ')
job = input('What is the job title of the empoyee? ')
personnel = Employee(name,id_num,department,job)
employee_list.append(personnel)
return employee_list
for item in employee_list:
print(item.get_name())
print(item.get_id())
print(item.get_department())
print(item.get_job())
print()
main()
You need to remove the following line in your main() function:
return employee_list
It is causing your main to stop running without ever reaching the printing for loop.

How to make a function that calls aand prints each students name and courses

Here is what i have so far
from CSE_324_course import Course
from CSE_324_skeleton_student import Student
math = Course("Algebra I")
language = Course("Spanish I")
science = Course("Earth Science")
history = Course("U.S. History I")
phys_ed = Course("Physical Education I")
speaking = Course("Speech I")
art = Course("Art I")
test_student = Student("Jill", "Sample")
test_student.add_course(math)
test_student.add_course(language)
test_student.add_course(science)
test_student.add_course(history)
test_student2 = Student("Bill", "Sample")
test_student2.add_course(math)
test_student2.add_course(phys_ed)
test_student2.add_course(science)
test_student2.add_course(history)
test_student3 = Student("Kim", "Sample")
test_student3.add_course(language)
test_student3.add_course(speaking)
test_student3.add_course(science)
test_student3.add_course(art)
student_list=[test_student,test_student2,test_student3]
for (test_student,test_student2,test_student3 : get_course)
if (test_student().equals(search))
System.out.println(teststudnetgetCourse());
#Each iteration should:
#get,concatenate, and print the first and last name of the student
#print all courses for that student
#print a blank line between students
'''for this part you may need to review the other skeleton code to:
- see how to get items from a list
- see if there is code (like a function) in that file you can call in this file
- verify that running this file gets you the correct output with information from that file
Also, review syntax of pulling items from a list f
2 page of code
Course import Course
class Student:
student_id = 0
def __init__(self, first_name, last_name):
self.first_name = first_name
self.last_name = last_name
self.courses = []
self.student_id = Student.student_id
Student.student_id += 1
def __str__(self):
# TODO You will need to use a variable in the loop, so you must intialize it here,
# that variable will need to be initalized to get items listed in the first def _init_ section
# TODO add a loop that will go through the course list
# TODO Add code here to create a string representation of a student,
# including first and last name and all courses that student is taking
return "complete this return statement based on your in loop variable"
def get_first_name(self):
return self.first_name
def get_last_name(self):
return self.last_name
def get_student_id(self):
return self.student_id
def add_course(self, new_course):
# TODO add code to append new_course to self.courses
print "Course not yet added, implementation needed."
3rd page
class Course:
def __init__(self, course_name):
self.course_name = course_name
def __str__(self):
return self.course_name
I think you are looking to change
for (test_student,test_student2,test_student3 : get_course)
if (test_student().equals(search))
System.out.println(teststudnetgetCourse());
(which you have improperly indented) to:
for student in student_list:
print("{} {}".format(student.first_name, student.last_name))
for course in student.courses:
print(course) # This won't work because "2 page of code Course import Course" needs to be finished
print("\n") # blank line between students

Getting an attribute error in Python

I know that there are a few post on Python attribute errors but I cannot find anything to help solve my issue or how to fix it. Here is my code:
class Employee:
def __init__(self, name, ID_number, dept, job_title):
self.__name = name
self.__ID_number = ID_number
self.__dept = dept
self.__job_title_number = job_title
#set methods
def set_name(self,name):
self.__name = name
def set_ID_number(self,ID_number):
self.__ID_number = ID_number
def set_dept(self,dept):
self.__dept = dept
def set_job_title(self,job_title):
self.__job_title = job_title
#get methods
def get_name(self):
return self.__name
def get_ID_number(self):
return self.__ID_number
def get_dept(self):
return self.__dept
def get_job_title(self):
return self.__job_title
def main():
emp1 = Employee("Susan Myers", 47899, "Accounting", "Vice President")
emp2 = Employee("Mark Jones", 39119, "IT", "Programmer")
emp3 = Employee("Joy Rogers", 81774, "Manufacturing", "Engineer")
print("Information for employee 1:")
print("Name:",emp1.get_name())
print("ID:",emp1.get_ID_number())
print("Department:",emp1.get_dept())
print("Job Title:",emp1.get_job_title())
main()
The traceback that I get is: Traceback (most recent call last):
File "C:/Users....", line 48, in
main()
File "C:/Users....", line 41, in main
print("Job Title:",emp1.get_job_title())
File "C:/Users....", line 29, in get_job_title
return self.__job_title
AttributeError: 'Employee' object has no attribute '_Employee__job_title'
In __init__, you use self.__job_title_number = job_title, but then in get_job_title you use self.__job_title, which at this point hasn't been set.
You need to make your variable name consistent across all uses.
You have not declared the member in the constructor
Must change
self.__job_title_number = job_title
to
self.__job_title = job_title
In your init function inside your class you have job title as self.__job_title_number but in the getter function you return self.__job_title. You have to change one of these so they are the same.

using a class instead of a list python

I have the following code:
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys import re
companies = {}
for line in open('/home/ibrahim/Desktop/Test.list'):
company, founding_year, number_of_employee = line.split(',')
number, name = company.split(")")
companies[name] = [name, founding_year, number_of_employee]
print "Company: %s" % company
CompanyIndex = raw_input('\n<Choose a company you want to know more about.>\n\n<Insert a companyspecific-number and press "Enter" .>\n')
if CompanyIndex in companies:
name, founding_year, number_of_employee = companies[CompanyIndex]
print 'The companys name is: ',name,'\nThe founding year is: ', founding_year,'\nThe amount of employees is: ', number_of_employee
else:
print"Your input is wrong."
This program reads some information from a text file which looks like this:
(1)Chef,1956,10
(2)Fisher,1995,20
(3)Gardener,1998,50
My aim is to get a class, where I can save the information about the company's name, the founding year, and the number of employees instead of using the dictionary which also contains a list.
I read several tutorials but I really do not know how to do that. It was really confusing what this "self" is what __init__ and __del__ does and so on. How do I go about doing this?
You can do:
class Company(object):
def __init__(self, name, founding_year, number_of_employee):
self.name = name
self.founding_year = founding_year
self.number_of_employee = number_of_employee
After that you can create a Company object by writing company = Company('Chef', 1956, 10).
Here's an example of how you could create a CompanyInfo class.
class CompanyInfo(object):
def __init__(self, name, founded_yr, empl_count):
self.name = name
self.founded_yr = founded_yr
self.empl_count = empl_count
def __str__(self):
return 'Name: {}, Founded: {}, Employee Count: {}'.format(self.name, self.founded_yr, self.empl_count)
And here's an example of how you might create it:
# ...
for line in open('/home/ibrahim/Desktop/Test.list'):
company, founding_year, number_of_employee = line.split(',')
comp_info = CompanyInfo(company, founding_year, number_of_employee)
And here's an example of how you might use it:
print "The company's info is:", str(comp_info)
class companies(object):
def __init__(self,text_name):
text_file = open(text_name,'r')
companies = {}
all_text = text_file.read()
line = all_text.split('\n') #line is a list
for element in line:
name,year,number = element.split(',')
companies[name] = [year,number]
self.companies = companies
def get_information(self,index):
print self.companies[index]
#an instance of the class defined above
my_company = companies(r'company.txt')
#call function of my_company
my_company.get_information(r'Gardener')
class Company:
def __init__(self, name, year_of_funding, num_of_employees):
'''
This is the constructor for the class. We pass the
info as arguments, and save them as class member variables
'''
self.name = name
self.year_of_funding = year_of_funding
self.num_of_employees = num_of_employees
def get_name(self):
'''
This method returns the company name
'''
return self.name
def get_year_of_funding(self):
'''
This method returns the year the company was funded
'''
return self.year_of_funding
def get_num_of_employees(self):
'''
This method returns the number of employees this company has
'''
return self.num_of_employees
Then you can create an instance of the class, and use the get methods to fetch the data:
my_company = Company('Microsoft', 1964, 30000)
print my_company.get_name() + ' was funded in ' + str(my_company.get_year_of_funding()) + ' and has ' + str(my_company.get_num_of_employees()) + ' employees'
# OUTPUT: Microsoft was funded in 1964 and has 30000 employees

Categories

Resources