I'm taking my first Python class so please bear with me, I have ZERO experience in programming but I'm very eager to learn. If you could steer me in the right direction I'd really appreciate it. Thank you in advance.
I've looked through previous questions but I wasn't able to find one that fully helped/explained where I'm getting stuck. I have a dictionary that stores team members(names, phone, jersey) and need to be able to write this to a file. Below is what I currently have, when I run this I get the error AttributeError:'dict' object has no attribute 'getname'.
class Member:
def get name(self):
return self.name
def get phone(self):
return self.phone
def get jersey(self):
return self.jersey
members={}
def saveData(members, filename):
filename=input("Filename to save:")
outFile=open(filename,"wt")
for x in members.keys():
name=members[x].getname
phone=members[x].getphone
jersey=members[x].getjersey
outFile.write(name+","+phone","+jersey+"\n")
print("Data Saved")
outFile.close()
Member class
You've put a space in the function name, so it won't work.
Too, you don't seem to have an __init__ function.
class Member:
def __init__(self, name, phone, jersey):
self.name = name
self.phone = phone
self.jersey = jersey
def get_name(self):
return self.name
def get_phone(self):
return self.phone
def get_jersey(self):
return self.jersey
Anyway, it's a lot easier that just don't make these get functions; the user can get the variables of a class using the dot syntax.
class Member:
def __init__(self, name, phone, jersey):
self.name = name
self.phone = phone
self.jersey = jersey
shell:
>>> member1 = Member("Dave", "123456789", "red")
>>> member.name
'Dave'
>>> member.phone
'123456789'
>>> member.jersey
'red'
saveData function
It won't work, you should do this:
def saveData(members): # don't include filename, it's going to be redefined later
filename = input("Filename to save: ") # space at the end
with open(filename, 'wt') as outFile: # using with for files is recommended
# then you don't need to close the file
for x in members: # you can directly iterate from a dict
name = x.get_name() # you didn't call the function at all
phone = x.get_phone() # members[x] not necessary
jersey = x.get_jersey()
outFile.write(name+", "+phone+", "+jersey+"\n") #missing + sign
print("Data Saved")
Working example
__init__.py
class Member:
def __init__(self, name, phone, jersey):
self.name = name
self.phone = phone
self.jersey = jersey
def get_name(self):
return self.name
def get_phone(self):
return self.phone
def get_jersey(self):
return self.jersey
def saveData(members):
filename = input("Filename to save: ")
with open(filename, 'wt') as outFile:
for x in members:
name = x.get_name()
phone = x.get_phone()
jersey = x.get_jersey()
outFile.write(name+", "+phone+", "+jersey+"\n")
print("Data Saved")
IDLE shell
>>> members = [Member("Dave", "123456789", "red"),
Member("Tom", "133742097", "yellow"),
Member("Elisa", "122333444", "blue"),
Member("John", "987654321", "blue")
]
>>> saveData(members)
Filename to save: output.txt
Data Saved
output.txt
Dave, 123456789, red
Tom, 133742097, yellow
Elisa, 122333444, blue
John, 987654321, blue
You can define getname, getphone in your Member class as follows:
class Member:
def getname(self):
return self.name
def getphone(self):
return self.phone
def getjersey(self):
return self.jersey
Then you can get values from getters in your saveData function :
name=members[x].getname()
phone=members[x].getphone()
jersey=members[x].getjersey()
Related
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.
I am getting attributeError, but I don't understand....
class User():
def __init__(self, first, last, age):
self.first = first
self.last = last
self.age = age
self.login_attempt = 0
class Admin(User):
def __init__(self, first, last, age):
super().__init__(first, last, age)
self.privilages = Privilages()
class Privilages():
def __init__(self, privilages = ''):
self.privilages = []
def show_privilages(self):
print("There are the privilages... : ")
if self.privilages:
for privilage in self.privilages:
print("- " + privilage)
else:
print("The user has no privilages. ")
sarah.privilages = ['can add post', 'can delete post']
sarah.privilages.show_privilages()
I am not sure what I am missing here, I used for loops to go over the list and print it out, however I keep getting error of "'list' object has no attribute 'show_privileges'"
You're assigning a list to sarah.privilages, so it surely does not have a show_privilages method. You should make the __init__ method of Admin take a list of privileges as a parameter, so it can pass on to the __init__ method of Privilages to initialize its privilages attribute:
class Admin(User):
def __init__(self, first, last, age, privilages):
super().__init__(first, last, age)
self.privilages = Privilages(privilages)
class Privilages():
def __init__(self, privilages):
self.privilages = privilages
def show_privilages(self):
print("There are the privilages... : ")
if self.privilages:
for privilage in self.privilages:
print("- " + privilage)
else:
print("The user has no privilages. ")
sarah = Admin('sarah','mary','smith', ['can add post', 'can delete post'])
sarah.privilages.show_privilages()
This outputs:
There are the privilages... :
- can add post
- can delete post
Write a separate Privileges class. The class should have one
attribute, privileges, that stores a list of strings.
Move the show_privileges() method to this class. Make a Privileges instance
as an attribute in the Admin class. Create a new instance of Admin and use your
method to show its privileges
class User():
"""Represent a simple user profile."""
def __init__(self, first_name, last_name, username, email, location):
"""Initialize the user."""
self.first_name = first_name.title()
self.last_name = last_name.title()
self.username = username
self.email = email
self.location = location.title()
class Admin(User):
def __init__(self, first_name, last_name, username, email, location):
super().__init__(first_name, last_name, username, email, location)
#Initialize an empty set of privileges.
self.privileges= Privileges()
class Privileges():
def __init__(self,privileges =[]):
self.privileges = privileges
def Show_privileges(self):
print("\nPrivileges: ")
if self.privileges:
for privilege in self.privileges:
print("- " + str(privilege))
else:
print("- this user has no privileges.")
eric = Admin('suraj', 'boi', 'e_mater', 'e_matthes100#example.com', 'alaska')
eric.describe_user()
eric.privileges.Show_privileges()
print("\nAdding privileges...")
eric_privileges = [
'can reset passwords',
'can moderate discussions',
'can suspend accounts',
]
eric.privileges.privileges = eric_privileges
eric.privileges.Show_privileges()
I am a beginner to OOP in python as I have not yet learned about it in school. I understand the basics, like you can haveself.variables and they are different for each time you use a class. But I do not know how to add to these variables as shown below:
class Person:
def __init__(self, fname, sname):
self.fname = fname
self.sname = sname
self.fullname = '{} {}'.format(fname, sname)
self.email = '{}.{}#email.com'.format(fname, sname)
class Teacher(Person):
def __init__(self, fname, sname, subject):
super().__init__(fname, sname)
self.subjects = subject
def add_subject(self, sub):
self.subjects.append(sub)
def del_subject(self, sub):
self.subjects.delete(sub)
class Student(Person):
def __init__(self):
super().__init__(fname, sname)
pass
t1 = Teacher('John', 'Becker', 'Maths')
print(t1.fullname)
t1.add_subject(input("Add Subject: "))
print('Subjects: ')
for i in t1.subjects:
print("=====> "+i)
When I run the code:
John Becker
Add Subject: A
Traceback (most recent call last):
File "C:/Desktop/Documents/YEAR 9/Computing/test.py", line 32, in <module>
t1.add_subject(input("Add Subject: "))
File "C:/Desktop/Documents/YEAR 9/Computing/test.py", line 17, in add_subject
self.subjects.append(sub)
AttributeError: 'str' object has no attribute 'append'
I also watched tutorials by Corey Schafer on Youtube, and I made sure to copy the style of his code exactly how he did it, but it still doesn't end up the same when I run it.
I have tried to make the self.subjects = subject.split(" "), and this works, but if i were to print the subjects of t1, it would print a list. Is there a way to alter the code in the class Teacher: so that the subjects are returned as a string rather than typing print(subjects.join(" ")) Every time?
Edit: Ignore class Student, It is not finished, and also the def del_subject.
The subject variable is initiated in the __init__ with the 3rd variable. In your example this is set to 'Maths', a string. Perhaps that needs to be a list of subjects? In that case you need to pass a list to the constructor. Then subjects will be a list and append will work when you call add_subject.
t1 = Teacher('John', 'Becker', ['Maths'])
print(t1.fullname)
t1.add_subject(input("Add Subject: "))
The main problem here is in your constructor for Teacher. For example t = Teacher('John', 'Doe', 'math') means that t.subjects is 'math', not ['math'].
To fix this you could either change it to:
class Teacher(Person):
def __init__(self, fname, sname, subject):
...
self.subjects = [subject]
Or you could have
class Teacher(Person):
def __init__(self, fname, sname, *subjects):
...
self.subjects = list(subjects)
Which will give the teacher the list of subjects passed in. So you'd have
>>> t = Teacher('John', 'Doe', 'math')
>>> t.subjects
['math']
>>> t2 = Teacher('Jane', 'Smith', 'history', 'biology')
>>> t2.subjects
['history', 'biology']
For the del_subject method, you'll need to use the list.remove method. The list class has no method delete.
Simplest way, as a beginner is:
class Teacher(Person):
def __init__(self, fname, sname, *subject):
super().__init__(fname, sname)
self.subjects = list(subject)
def get_subjects(self):
return ' '.join(self.subjects)
You can get a comma separated string of subjects using
return ','.join(self.subjects)
class Person:
def __init__(self, name):
self.name = name
self.bucket = []
def announce(self, *args):
# ???
pass
def put(self, item):
self.bucket.append(item)
p1 = Person("ya")
p2 = Person("yu")
p1.put("apple")
now I want to somehow announce to all Person() objects that I have an apple in my bucket, they should put one apple in their bucket too if they want.
Simple implementation could be:
class Person:
persons = set()
def __init__(self, name):
self.name = name
self.bucket = []
self.persons.add(self)
def announce(self, msg):
print("[{}]: {}".format(self.name,msg))
#classmethod
def broadcast(cls, person, msg):
for p in cls.persons:
if not p is person:
p.announce(msg)
def put(self, item):
self.bucket.append(item)
self.broadcast(self, '{}: got {} in my bucket!'.format(self.name, item))
p1 = Person("ya")
p2 = Person("yu")
p1.put("apple")
Person.broadcast(None, "Hey! Everybody can broadcast message!")
Output:
[yu]: "ya: got apple in my bucket!
[ya]: Hey! Everybody can broadcast message!
[yu]: Hey! Everybody can broadcast message!
That implementation lacks in
No deregister implementation
No thread save
Just Person and it's subclass can be informed
It is just a toy, you need to adapt it to your real case
Maybe is better you implement an Observer pattern better than that simple one.
Implementing the observer-pattern in python is quite simple,
The basic idea "I want Object A, object B, Object C to get notifications from a specified messaging Object". Therefore you somehow have to connect them, in observer Pattern this process is called "subscription". So your Object A, B, C (Observers) are subscribing to the Object that delivers messages (Subject)
This example is a basic implementation. I didn't addapt it to your code, but alice and bob would be Persons in your case.
class Mailbox :
def __init__(self, ownersName):
self.owner = ownersName
self.messages = []
self.newMessageObservers = []
def deliverMessage(self, message):
self.messages.append(message)
for notifyNewMessage in self.newMessageObservers:
notifyNewMessage(message, self.owner)
def subscribe(self, observer):
self.newMessageObservers.append(observer)
class MailboxObserver :
def __init__(self, observerName):
self.name = observerName
def newMessageHandler(self, contents, owner):
print self.name + " observed a new message in " +\
owner + "'s mailbox"
print "The message said: " + contents
# create the observers
alice = MailboxObserver("alice")
bob = MailboxObserver("bob")
# create a mailbox
alicesMailbox = Mailbox("alice")
# have bob and alice subscribe to alice's mailbox
# registering their 'newMessageHandler' method
alicesMailbox.subscribe(bob.newMessageHandler)
alicesMailbox.subscribe(alice.newMessageHandler)
# put a new message into alice's mailbox
alicesMailbox.deliverMessage("Hello, world!")
source: http://www.philipuren.com/serendipity/index.php?/archives/4-Simple-Observer-Pattern-in-Python.html
Just keep a normal variable in your class (Not a member), and update it whenever you want to "announce" something to all classes.
class Person:
bApple = False
def __init__(self, name):
self.name = name
self.bucket = []
def announce(self, *args):
# ???
pass
def put(self, item):
self.bucket.append(item)
def hasApple(self):
if Person.bApple:
return "True"
else:
return "False"
p1 = Person("ya")
p2 = Person("yu")
p1.put("apple")
print "p1 has Apple? " + p1.hasApple()
print "p2 has Apple? " + p2.hasApple()
Person.bApple = True
print "p1 has Apple? " + p1.hasApple()
print "p2 has Apple? " + p2.hasApple()
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