Python returning from class [closed] - python

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.

Related

Why am I getting a TypeError when I seem to be filling the paremeters? [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 am trying to create an object and I'm initializing it with 2 fields first (name & number). However each time I run the program I'm given this error:
TypeError: __init__() missing 1 required positional argument: 'number'
The __init__ method in the class looks like this:
def __init__(self, name, number):
self.__name__ = name
self.__number__ = number
The code where I try to create the object is this:
employee1 = ProductionWorker(Employee)
name = input("Enter employee name:")
number = input("Enter employee number:")
employee1.__init__(name, number)
Does anyone know why I may be getting this error?
Do:
name = input("Enter employee name:")
number = input("Enter employee number:")
employee1 = ProductionWorker(name, number)
You do not generally need to call __init__ explicitly; it's invoked by the ProductionWorker(...) expression, which passes its arguments to self.__init__ as part of initialization.
You do not need to restate when constructing a new object that Employee is the parent class; that only needs to be said when the class is defined.
You are using the class as a parameter.
Then, init is always automatically called on creation. This how it might work as You want (using the show method to validate):
class Employee:
def __init__(self, name, number):
self.__name__ = name
self.__number__ = number
def show(self):
print(self.__name__)
print(self.__number__)
name = input("Enter employee name:")
number = input("Enter employee number:")
employee1 = Employee(name,number)
employee1.show()

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

how assign list attributes to a class python 3 [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 5 years ago.
Improve this question
I need to create a class student and then assign him or her a subject (maths, science, etc.) and then the grade by subject.
Basically, I have created a class student with name, gender,etc. Then I need to add more than one subject.
But i dont understand how one student object can get more than one subject and probably a greade per subject.
class student:
def __init__(self,name,age,gender,subject):
self.name = name
self.age = age
self.gender = gender
self.subject = subject
def __str__(self):
return ('{},{},{},{}'.format(self.name,self.age,self.gender,self.subject))
new = student('Alan',17,'M','Science')
Please if someone can help me to clarify a little bit I appreciate.
thanks
From your question, I gather that you have already worked with entity relations (ERDs), which is why you are thinking in terms of associations -- which is good. I'm assuming this is homework, so I don't want to give away too much. However, the code below should get you started.
from typing import List, Dict
class CollegeClass:
def __init__(self, class_code: str, name: str):
self.class_code = class_code #type: str
self.name = name
def __str__(self):
return f"{self.class_code}, {self.name}"
def __repr__(self):
return str(self)
class Student:
def __init__(self):
self.current_classes = dict() # type: Dict[str, CollegeClass]
def enroll(self, college_class: CollegeClass):
if college_class.class_code in self.current_classes:
print("The student is already taking the class.")
return
self.current_classes[college_class.class_code] = college_class
if __name__ == '__main__':
math = CollegeClass("mth101", "Intro to Math")
english = CollegeClass("eng201", "Intro to Fiction")
eric_praline = Student()
eric_praline.enroll(math)
eric_praline.enroll(english)
for _, cls in eric_praline.current_classes.items():
print(cls)
There are many ways to accomplish this task. One solution is to not specify the subject when creating the student. Instead, you would create the student object and then add subjects to it.
For example:
student = Student(name="John Smith")
for subject_name in ("Math", "Science", "Literature"):
student.add_subject(subject_name)
That gives you a new student who has three subjects. The add_subject method might look something like this:
class Student(object):
def __init__(self, name, age, gender):
...
self.subjects = {}
...
def add_subject(self, name):
self.subjects[name] = Subject(name)
To assign grades you would do something like this, perhaps
student.add_grade("Math", "A")
student.add_grade("Science", "B")
student.add_grade("Literature", "C")
add_grade would then take the grade name, look up the subject object from self.subjects, and call a method on that subject object to add the grade.
For example:
def add_grade(self, subject_name, grade):
subject = self.subjects[subject_name]
subject.add_grade(grade)
Your class Subject could be something very simple:
class Subject(self):
def __init__(self, name):
self.name = name
self.grade = None
def add_grade(self, grade):
self.grade = grade
Note: the above assumes you want a single grade per subject. If you want multiple grades, you can change self.grade to be self.grades and have it be a list.
Class Student represents just a type of people
Object of class Student represents a particular student, e.g. John Smith
Class Subject represents something students can learn in general
Object of class Subject represents a particular class students can take, e.g. Math 2017
Grade does not belong in either of these, because it only makes sense with a combination of both. So I would suggest creating some data storage, e.g. a list of tuples to store a grade for each combination of student/subject objects you want to keep track of, e.g.
Grades = [
(john_smith, math_2017, 'A+'),
...
]
class Subject(object):
def __init__(self, name, grade=None):
self.name = name
self.grade = grade
class student:
def __init__(self,name,age,gender, subjects=[]):
self.name = name
self.age = age
self.gender = gender
self.subjects = {}
for sub in subjects:
self.subjects[sub] = Subject(sub)
# Create new student with 2 subjects (Art and Science)
new = student('Alan',17,'M', subjects=['Art', 'Science'])
# You can wrap the following processes in functions if so desired
# Add a new subject later on (Math)
new.subjects['Math'] = Subject('Math')
# Add grades
new.subjects['Art'].grade = 'C'
new.subjects['Science'].grade = 'A+'
new.subjects['Math'].grade = 'B-'
# Get a list of subjects and grades
print([(sub.name, sub.grade) for _, sub in new.subjects.items()])
>>>[('Art', 'C'), ('Science', 'A+'), ('Math', 'B-')]
But i [don't] understand how one student object can get more than one subject and probably a [grade] per subject.
Pass in a dictionary of {subject: grade} pairs.
Code
class Student:
def __init__(self, name, age, gender, subjects=None):
self.name = name
self.age = age
self.gender = gender
# Handle mutable keyword defaults
if subjects is None:
self.subjects = {}
else:
self.subjects = subjects
def __repr__(self):
return ("{0.name}, {0.age}, {0.gender}, {0.subjects}".format(self))
subjects = {"Math": "A", "Biology": "B-", "Chemistry": "A"}
s = Student("Joe", 20, "M", subjects=subjects)
s
# Joe, 20, M, {'Math': 'A', 'Chemistry': 'A', 'Biology': 'B-'}
s.subjects["Math"]
# 'A'
Assigning None to a keyword argument is a convention for avoiding a well-known gotcha when assigning mutable arguments, e.g. lists, dictionaries. The lines that handle subjects is equivalent to this one-liner:
self.subjects = {} if subjects is None else subjects
The __repr__() method was defined, which you may wish to include along with __str__().

Python Object Oriented Programming

I have to write a program to demonstrate a customer using their credit card to check out, I have spent a few hours trying to figure out how to do it and have provided my code below.
I have to make a class, then use it in a main function.
This is what I have so far:
class Customer:
def __init__(self, customer_name, credit_card_num, credit_security_code, debit_card_num, debit_pin):
self.customer_name = name
self.credit_card_num = credit_num
self.credit_security_code = credit_code
self.debit_card_num = debit_num
self.debit_pin = debit_pin
def inputCardInfo(self):
self.customer_name = str(input("Enter your name: "))
self.credit_card_num = str(input("Enter credit card Number: "))
self.credit_security_code = str(input("Enter 3-digit security code: "))
self.debit_card_num = str(input("Enter debit card number: "))
self.debit_pin = str(input("Enter 4-digit PIN: "))
then the main function:
from customer import Customer
def main():
print("Welcome to Wake-Mart. Please register.")
customer_name = input("enter name: ")
customer1 = Customer(customer_name)
print("Registration completed")
main()
I don't know the correct way to call the class methods. I feel if I can figure out how to make one of these work I can figure out the rest.
If you want to understand behaviors and properties more deeply I would recommend making a separate behavior for each value. (get_credit_num, get_debit_num, etc.)
Then, in your main, just call each function individually to get each value.
And to clarify, "class functions", or behaviors, are just things an object can do. You call them the same way you would any function, with the only difference being you put the name of the instance you are calling this behavior for before the function to replace "self". So if you were calling "InputCardInfo" for the object customer1, you would do it like so:
customer1.InputCardInfo(other parameters)
Your code as-is will not work because you are not passing all required parameters when initializing your class.
customer1 = Customer(customer_name)
All of the additional parameters besides self included in your def __init__(self, var1, var2, var3): needs to be passed to the class instance when initializing. There are also variable naming issues with your code but I hope my example below clarifies things for you.
A quick note first to help you better understand: self.customer_name = name does not make sense in your code because there is no parameter named name included in the __init__() method. You must associate an instance variable (self.whatever) to a known variable name passed in through the __init__(self, external_var) method so that self.whatever = external_var. Then, and only then, can you use class methods to call self.whatever and expect to receive the data you passed from external_var. Also, additional parameters you include after self in __init__(self, ..., ...) MUST be passed as variables when creating a class instance.
class Customer:
def __init__(self, customer_name, credit_card_num, credit_security_code, debit_card_num, debit_pin):
self.customer_name = customer_name
self.credit_card_num = credit_card_num
self.credit_security_code = credit_security_code
self.debit_card_num = debit_card_num
self.debit_pin = debit_pin
name = 'Mike'
cc_num = '0000 0000 0000 0000'
code = '111'
debit_num = '1111 1111 1111 1111'
pin = '1234'
new_customer = Customer(name, cc_num, code, debit_num, pin)

How do i store multiple object attibutes to a single dictionary key?

I'm fairly new to the world of python and programming in general, and its rare that i get up the nerve to ask questions, but I'm stomped so i thought id suck it up and ask for help.
I'm making an Address book.
class Person():
def __init__(self,name,number,email):
self.name = name
self.number = number
self.email = email
contact = Person('Mike','1-800-foo-spam','email#email.com')
My question is how would go about storing all these attributes in a dictionary with contact.name as the key and contact.number and contact.email as the values.
Bonus question.
Should the dictionary be outside the class, perhaps in the main function?
or
Does it need to be a class variable(not completely sure how those work)
or an object variable
something like
self.storage = {}
Any help would be greatly appreciated.
Thank you!
If I put this information in a dictionary, I would do it like that:
class Person():
def __init__(self,name,number,email):
self.name = name
self.number = number
self.email = email
self.storage = {self.name: [self.number, self.email]}
def getStorage(self):
return self.storage
contact = Person('Mike','1-800-foo-spam','email#email.com')
print contact.storage
# or
print contact.getStorage()
But the whole idea of a dictionary is to have a number of keys and corresponding values. In this example, it always will be one only. So, another schema comes to my mind:
class Person():
def __init__(self,name,number,email):
self.name = name
self.number = number
self.email = email
# creating some example contacts
c1 = Person('Mike','1-800-foo-spam','email#email.com')
c2 = Person('Jim','1-700-foo-spam','e111mail#email.com')
c3 = Person('Kim','1-600-foo-spam','e222mail#email.com')
# creating a dictionary to fill it with c1..cn contacts
contacts = {}
# helper function to automate dictionary filling
def contactToDict(list_of_contacts):
for item in list_of_contacts:
contacts[item.name] = (item.number, item.email)
contactToDict([c1, c2, c3])
"""
expected output:
Mike: ('1-800-foo-spam', 'email#email.com')
Jim: ('1-700-foo-spam', 'e111mail#email.com')
Kim: ('1-600-foo-spam', 'e222mail#email.com')
"""
for key, val in contacts.items():
print str(key) + ": " + str(val)
The answer to the title of the question: a value should be a type of object with allows to have a "list" inside (i.e. list, tuple, another dictionary or custom type object having a number of attributes.)
You can pretty easily have a dictionary with tuples as the values.
a = {}
a["bob"] = ("1-800-whatever","bob#gmail.com")
If you wanted to make it a class variable, you'd just need to create an empty dictionary as part of the Person class:
class Person():
storage = {}
Then in __init__ you can store the new person's info in that dictionary:
def __init__(self,name,number,email):
self.name = name
self.number = number
self.email = email
Person.storage[name] = (number, email)
As you can see class attributes are accessed with the classname, but otherwise like any other attribute. You could store them as a tuple or a list if you need to update them. However if you intend to make changes, it might be better to store the actual Person object, to save having to update Person.storage and the actual person at the same time. This is even easier to do:
def __init__(self,name,number,email):
self.name = name
self.number = number
self.email = email
Person.storage[name] = self
self refers to the instance of Person that's being created with __init__. That's Mike in your example. Then you could access their values by attribute:
Person.storage["Mike"].number
Also as Kevin pointed out in a comment you might want to detect if the key already exists to avoid overwriting an old entry (eg. if there's already a Mike in the dictionary):
self.email = email
if name in Person.storage:
# Make unique name
Person.storage[name] = (number, email)

Categories

Resources