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
Related
I am new to pyhton and also new to working with classes. I am working on the below problem where I want to multiply the class variable (raise_amount) by the instance salary. However, when i do this, I get None as output. I would like to get the salary amount per person multiplied by 1.04. Any help will be greatly appreciated.
class Person:
raise_amount = 1.04
def __init__(self, name, street_name, house_nr, post_code, salary): #:post_code, salary):
self.name = name
self.street_name = street_name
self.house_nr = house_nr
self.post_code = post_code
self.salary = salary
def street_name_and_house_nr(self):
return '{} {}'.format(self.street_name, self.house_nr)
def apply_raise(self): # here is the code that seems to have problems
self.salary = int(Person.raise_amount * self.salary)
def street_name_and_house_nr_salary(self):
return self.name + ' ' + str(self.salary)
prs_1 = Person("Mary's", 'Broadway', 304, '2526 CG', 10)
prs_2 = Person("Jhon's", 'Longstreet', 304, '2829 AK',7)
prs_3 = Person("Larry's", 'Chinstreet', 58, '3046 JP', 8)
print(Person.apply_raise(prs_1))
print(Person.apply_raise(prs_2))
print(Person.apply_raise(prs_3))
This is the output i get when i run the code
None
None
None
apply_raise() doesn't return the new salary, it just updates the salary attribute. So you should get that separately to print it.
prs_1.apply_raise()
print(prs_1.salary)
Other notes:
Conventionally the first argument to methods is self. Don't make up your own name (what does lelf mean?).
You should call methods using instance.method(), not Class.method(instance). This ensures that the proper method will be used when the instance is in a subclass.
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.
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
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
I'm having trouble finishing this program. The goal of the program is to read a file that contains the abbreviation of a stock and a number that stands for the amount of shares. I am then going to put the full company name, price of the stock, number of shares, and total investments in an html file in a table. I am having trouble separating the abbreviation of the company from the number of shares in the text file. This is what I have so far:
from string import *
import urllib2
class getURLinfo:
def __init__( self ):
"""Constructor, creates the object and assigns "None" to the
instance variables."""
self.url = None
self.begMarker = None
self.endMarker = None
def setURL( self, u ):
"""Mutator: assign value to the instance variable, URL"""
self.url = u
def setMarkers( self, begin, end ):
"""Mutator: assign values to the instance variables begMarker
and endMarker"""
self.begMarker = begin
self.endMarker = end
def getInfo( self, identifier ):
"""Return the text between the two markers for the specific URL
indicated by the 'identifier' parameter."""
# Create the exact URL string and retrieve the indicated html text
f = urllib2.urlopen( self.url % identifier )
html = f.read()
# Locate the markers in the htmlText string
begIndex = html.find( self.begMarker )
endIndex = html.find( self.endMarker, begIndex )
# Include some simple error checking if the markers are not found
if begIndex== -1 or endIndex== -1:
return None
# Advance the starting index to the actual beginning of the desired text
begIndex = begIndex + len( self.begMarker )
# Slice out and return the desired text
return html[ begIndex : endIndex ]
# ---------------------------------------------------------
# Testing Area
# ---------------------------------------------------------
"""
if __name__=="__main__":
# Create an object of type getURLinfo
zodSite = getURLinfo()
# Initialize the instance variables
zodSite.setURL("http://my.horoscope.com/astrology/free-daily-horoscope-%s.html")
zodSite.setMarkers('id="textline">',"</div>")
# Retrieve the horoscope and display it
horos = zodSite.getInfo("capricorn")
print "Your horoscope is: \n",horos
"""
"""
Class definition for a list of stocks.
Instance variables: name and price
"""
class STOCKINFO:
def __init__(self):
#This is the constructor for class FriendInfo
self.abbrev = None
self.share = None
self.name = None
self.price = None
def otherInfo(self, ab, sh):
self.abbrev = ab
self.share = sh
def newInfo(self, nm, pr):
#Enters the stock information
self.name = nm
self.price = pr
def updateAbbrev(self, newAb):
self.abbrev = newAb
def updateShare(self, newSh):
self.share = newSh
def updateName(self, newNm):
self.name = newNm
def updatePrice(self, newPr):
self.price = newPr
def getAbbrev(self):
return self.abbrev
def getShare(self):
return self.share
def getName(self):
return self.name
def getPrice(self):
return self.price
def showInfo(self):
print "This stock's info is:\n\t%s\n\t%s\n\t%s\n\t%s" \
% (self.name, self.price)
#---------------------------------------------------------
# Testing Area
"""
if __name__ == "__main__":
print "\n\nCreating new information entries..."
f1 = STOCKINFO()
f2 = STOCKINFO()
print "\nFilling in data"
f1.newInfo('GOOG', '75', 'Google', '544.26')
f2.newInfo('GM', '12','General Motors', '32.09')
print "\nPrinting information in datatbase"
f1.showInfo()
f2.showInfo()
print "\nUpdating the information"
f1.updateAbbrev('GE')
f2.updateShare('500')
f1.updateName('Google')
f2.updatePrice('544.10')
print "\nShowing the updated info \n"
f1.showInfo()
f2.showInfo()
print
print "Using the getXX() methods..."
print "getAbbrev = ", f1.getAbbrev()
print "getShare = ", f1.getShare()
print "getName = ", f1.getName()
print "getPrice = ", f1.getPrice()
"""
def openHTML():
"""
This function creates and opens the HTML called "stock.html"
and returns the variable file1 at the end.
"""
file1 = open("stock.html", 'w')
file1.write("""\n<center><FONT COLOR="#00FF00"><html>\n<head><title>Stock \
Portfolio</title></head>""")
return file1
def Title(file1):
"""
This function creates a title on the webpage.
"""
file1.write("""<body bgcolor="#151B8D">
<h1>Stock Portfolio</h1>
<p>My total portfolio value is: </p>""")
def closeHTML(file1):
"""
This function will close the html file.
"""
file1.close()
def getStocks():
file2= open("stock.txt", 'r')
slist = []
for word in file2:
stock = word[:-1]
slist.append(stock)
print "The stocks you have are:"
print slist
return slist, file2
def getStocksURL(slist):
stockInfo = STOCKINFO()
sURL = getURLinfo()
sURL.setURL("http://finance.yahoo.com/q?s=%s")
sURL.setMarkers("""</b></span> </div><h1>""", "<span>")
name = sURL.getInfo(slist)
print "Company name: ", name
sURL.setMarkers("""</small><big><b><span id="yfs_l10_""", "</span></b>")
price = sURL.getInfo(slist)
print "Stock price is: ", price
stockInfo.newInfo(name, price)
return stockInfo
def stockInformation(slist):
stocklist = []
for stock2 in slist:
stockInfo = getStocksURL(stock2)
stocklist.append(stockInfo)
#print stocklist
return stocklist
def createTable (file1, Stocks):
file1.write("""<p>
<table border="1">
<tr>
<td>Company Name</td>
<td>Stock Price</td>
<td>Number of Shares</td>
<td>Total Investment</td>
</tr>""")
for stock in Stocks:
file1.write("""<tr>
<td>""" + str (stock.getAbbrev()) +"""</td>
<td>""" + str (stock.getShare()) + """</td>
<td>""" + str (stock.getName()) + """</td>
<td>""" + str (stock.getPrice()) + """</td>""")
def main():
f = openHTML()
Title(f)
slist = getStocks()
stocks = stockInformation(slist)
createTable(f, stocks)
closeHTML(f)
main()
Thank you!!
You said you are "having trouble separating the abbreviation of the company from the number of shares in the text file." What trouble, exactly?
To read in 2 columns of whitespace-separated data from a textfile, just do:
import fileinput
for line in fileinput.input(yourinputfile):
(abbrev,shares) = line.split() # if you want 2 fixed columns
#... lookup name, price...
slist.append(STOCKINFO(name,price,abbrev,shares)) # or whatever processing
Sounds like what you want, I can't see any problem?
(As the others said, delete all your code except for the parts that show the problem.)
(Or if you wanted 4 fixed columns: (name,price,abbrev,shares) = line.split(maxsplit=4))
(Or if you want 2-4 variable columns (with the last 2 being optional), you could use re.match, as below.)
If none of this is what you want, explain why it is not!, show sample input, and explain the error/problem you see.
import re
stocklist_pat = re.compile('(\S+)\s+(\S+)\s+(\S*)\s*(\S*)\s*')
(name,price,abbrev,shares) = stocklist_pat.match(line).groups()
Not directly related to your specific question, a couple of other stylistic comments, to make your code more Pythonic:
STOCKINFO has a 0-arg constructor, as well as two other 2-arg constructor-like methods newInfo() and otherInfo(). A 0-arg constructor doesn't make much sense since we know we're always going to immediately supply nm, pr, so define a 4-arg constructor and make ab,sh optional:
def __init__(self,nm,pr,ab=None,sh=None):
self.name = nm
self.price = pr
self.abbrev = ab
self.share = sh
Read about Python properties, it's easier than writing all those getters/setters (updateAbbrev/Share/Name/Price, getAbbrev/Share/Name/Price). "Python Is Not Java", for general style migration see the links at Programming in Python vs. programming in Java.