what am i doing wrong with these classes and objects [closed] - python

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
Write a program to store student details in a class. The information should include a
studentnumber, first name, surname and username.
Include a function that returns the e-mail address of the student. You construct the emaila ddress by adding "#coventry.ac.uk" to the username. So, Joe Blogs, with username
blogsj would get the e-mail address blogsj#coventry.ac.uk
2 Task 2
Create a program that uses the class from task 1 to collect a list of student records from
the user and allow them to be listed, with e-mail addresses.
You should include a menu system for the user.
#Python Lab9 Task1 & Task2
class student(object):
def _init_(self,student_ID,name,surname,username):
self.student_ID = student_ID
self.name = name
self.surname = surname
self.username = username
def email(self):
return self.username, "#coventry.ac.uk"
def _str_(self):
return "%d %s %s %s"%(self.student_ID,self.name,self.surname,self.username)
if __name__ == '__main__':
students=[]
user=""
while user not in ["Q","q"]:
print "Menu"
print "1. Show student detail"
print "2. Create new student detail"
print "3. Quit"
user=raw_input(">")
if user=="1":
for i in students:
print i
elif user=="2":
print "Creating a new student detail"
print "-----------------------------"
student_ID=raw_input("Student ID:")
name=raw_input("First Name:")
surname=raw_input("Surname:")
username=raw_input("Username:")
s = student(student_ID,name,surname,username)
students.append(s)
elif user=="3":
exit

You need double underscores for __init__ and __str__:
class student(object):
def __init__(self,student_ID,name,surname,username):
...
def __str__(self):
Here is a reference.
Also, exit won't work unless you invoke it by placing () after it:
elif user=="3":
exit()
Finally, because self.student_ID will be a string, you need to replace the %d on this line with %s:
return "%s %s %s %s"%(self.student_ID,self.name,self.surname,self.username)
%d is only used for integers.

Related

Python Output Gives Object Address Instead of Values [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I'm having a bit of trouble with this assignment, here's my current code.
This is the Class for the employees on a separate python file.
class Employee:
#Initializes the classes for the employee information
def __init__(self, name, id_number, department, title):
self.set_name = name
self.set_id_number = id_number
self.set_department = department
self.set_title = title
#Sets attributes to the information
def set_name(self, name):
self.name = name
def set_id_number(self, id_number):
self.id_number = id_number
def set_department(self, department):
self.department = department
def set_title(self, title):
self.title = title
#Returns the information's attributes
def get_name(self):
return self.name
def get_id_number(self):
return self.id_number
def get_department(self):
return self.department
def get_title(self):
return self.title
def __str__(self):
return 'Name:' + self.name + \
'\nID Number:' + self.id_number + \
'\nDepartment:' + self.department + \
'\nJob Title:' + self.title
Here is the main code that is supposed to print the information about the employees:
import employee
def main():
#Creates the three instances of the employees
emp1=employee.Employee("Susan Meyers", "47899", "Accounting", \
"Vice President")
emp2=employee.Employee("Mark Jones", "39119", "IT", "Programmer")
emp3=employee.Employee("Joy Rogers", "81774", "Manufacturing", \
"Engineer")
#Prints information about the employees
print("EMPLOYEE INFORMATION:")
print("---------------------")
print("Employee 1:")
print(emp1, '\n')
print("Employee 2:")
print(emp2, '\n')
print("Employee 3:")
print(emp3, '\n')
main()
This is the output I get when I run the 2nd file on this post:
EMPLOYEE INFORMATION:
---------------------
Employee 1:
<employee.Employee object at 0x000002BE14A959D0>
Employee 2:
<employee.Employee object at 0x000002BE14ABB0A0>
Employee 3:
<employee.Employee object at 0x000002BE14B622B0>
Not sure why this is happening, but if anyone could help, it would be much appreciated.
The string conversion function is __str__, not _str_. Adding a _ before and after should fix your problem.
More feedback, while not related to the question:
Use the following to call your main() instead. While not absolutely necessary, it is good practice. It prevents main() from being run if you use the .py file in an import statement.
if __name__ == "__main__":
main()
In the constructor of your class, the usage of the setter functions is incorrect. You need to call them instead of setting them.
Afterwards, it should work:
https://ideone.com/2mnd3g

can two different methods have different args in a class? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I want to add the age for users in a different method but some users might not have an age argument
class User:
"""a class to save info about every user """
def __init__(self, user_name, num_id):
self.name = name
self.mun_id = num_id
def age(self, age):
self.age = age
user1 = User("martin", "1")
print (user1.name)
Yes you can set user age separately. Example below:
user1.age(20)
print (user1.age)
#20 will print
define age = None like below and this optional argument should be the last one:
def age(self, age = None):

Python returning from class [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
class Customer: #at this part ı defined the class for the customers in the file
def __init__(self, Name, Surname, Age, Balance):
self.name = Name;
self.sname = Surname;
self.age = Age;
self.balance = Balance;
def __str__(self):
return("Hello, "+str(self.name)+" "+str(self.sname)+" You have "+ str(self.balance)+" dollars in your account.");
Hello, you can see my class above
My aim - ask users name/surname and get the str part in the class.
I'm getting informations about customers from csv file.
ans = input("name")
ans2 = input("surname")
a = Customer(ans,ans2)
print(a)
With this part I've tried to do part that I explained above but I could'nt make the code work.
You have to define all the other attributes the class instance supposed to have that is Name, Surname, Age, Balance where you have only given Name and Surname. Python will also expect all other attributes you have given in __init__
Take this for example:
Age = input("age") #add these to take input too
Balance = input("balance") #add these to take input too
a = Customer(ans,ans2, Age, Balance)
Well, if your values sometimes supposed to be empty, make some values not necessary as in example:
class Customer:
def __init__(self, Name, Surname, Age=None, Balance=None): # specify the values which would be left as blank
self.name = Name;
self.sname = Surname;
self.age = Age;
self.balance = Balance;
# another code here
Then, if you pass only part of data to class constructor, you'll still get a working class instance without any errors:
>>> a = Customer('Name', 'Surname')
>>> a.Name
'Name'
>>> a.Surname
'Surname'
>>> a.Age
>>> # we got None here
Of course, you can use keyboard input too to enter the values, which is not provided by your csv data file by using the input() function.

Python Classes and Inheritance [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm studying Python programming and I'm having difficulty understanding Inheritance. My assignment is to:
Create a Division and Department class.
Create a method named “getList()” which will display a message, “The
dept department has fullTime full-time and partTime part-time
instructors.”
In the “Department” class, assign 12 as value to the fullTime
variable, assign 27 to partTime, and “CIS” to dept. DO NOT create
any method in the “Department” class. and
Create an instance (object) of the “Department” class named
“myDept”. Use this “myDept” object to call the “getList()” method of
“Division” class (through Inheritance).
Here's what I have so far.
class Division():
def __init__(self, dept, fullTime, partTime):
self.dept = dept
self.fullTime = fullTime
self.partTime = partTime
def getList(self):
return "The (0) department has (1) full-time and (2) part-time instructors.".format(self.dept, self.fullTime, self.partTime)
class Department(Division):
myDept = Division(CIS247, 12, 27)
class Division(object):
def __init__(self,dept, fullTime, partTime):
self.fullTime = fullTime
self.partTime = partTime
self.dept=dept
def getList(self):
return "The {0} department has {1} full-time and {2} part-time instructors.".format(self.dept, self.fullTime, self.partTime)
class Department(Division):
pass
myDept = Department("CIS",12,37)
print myDept.getList()
Edited, I missed the "CIS", for string formatting you use {} not ().
Also " DO NOT create any method in the “Department” class." so removed init method.
python classes tutorial

How do i create objects of data in a file ?? python [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Improve this question
Suppose I have a file named abc.txt which contains the following data
Nathan Johnson 23 M
Mary Kom 28 F
John Keyman 32 M
Edward Stella 35 M
How do i create the objects of the data(records) in the file ?
Code which i have done . I am not getting of jow to create objects of data in a file
class Records:
def __init__(self, firstname, lastname, age, gender):
self.fname = firstname
self.lname = lastname
self.age = age
self.gender = gender
def read(self):
f= open("abc.txt","r")
for lines in f:
print lines.split("\t")
What should i do further ? I am an newbie in python and this task has been given to me. PLease help me out ?
Although you've used an object here, namedtuple would have been more suitable.
# Creating the class
class Records:
def __init__(self, firstname, lastname, age, gender):
self.fname = firstname
self.lname = lastname
self.age = age
self.gender = gender
# Using open to open the required file, and calling the file f,
# using with automatically closes the file stream, so its less
# of a hassle.
with open('object_file.txt') as f:
list_of_records = [Records(*line.split()) for line in f] # Adding records to a list
for record in list_of_records:
print record.age # Printing a sample

Categories

Resources