Python Output Gives Object Address Instead of Values [closed] - python

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

Related

Can't get python class initialized correctly [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 10 months ago.
Improve this question
I'm not sure why this isn't working. The error says my Artist object has no attribute called name. This doesn't make sense to me because I'm looking right at the attribute called name....
Define the Artist class with a constructor to initialize an artist's
information and a print_info() method. The constructor should by
default initialize the artist's name to "None" and the years of birth
and death to 0. print_info() should display Artist Name, born XXXX if
the year of death is -1 or Artist Name (XXXX-YYYY) otherwise.
Define the Artwork class with a constructor to initialize an artwork's
information and a print_info() method. The constructor should by
default initialize the title to "None", the year created to 0, and the
artist to use the Artist default constructor parameter values.
Ex: If the input is:
Pablo Picasso
1881
1973
Three Musicians
1921
the output is:
Artist: Pablo Picasso (1881-1973)
Title: Three Musicians, 1921
If the input is:
Brice Marden
1938
-1
Distant Muses
2000
the output is:
Artist: Brice Marden, born 1938
Title: Distant Muses, 2000
My code:
class Artist:
def __init__(self, name= "None", birth_year = 0, death_year = 0):
name = self.name
birth_year = self.birth_year
death_year = self.death_year
# TODO: Define constructor with parameters to initialize instance attributes
# (name, birth_year, death_year)
def print_info(self):
if self.death_year == -1:
print("{}, born {}".format(self.name,self.birth_year))
else:
print("{} ({}-{})".format(self.name,self,birth_year,self.death_year))
# TODO: Define print_info() method. If death_year is -1, only print birth_year
class Artwork:
def __init__(self,title ="None",year_created = 0, artist=Artist().name):
title = self.title
year_created = self.year_created
artist = self.artist
# TODO: Define constructor with parameters to initialize instance attributes
# (title, year_created, artist)
def print_info(self):
print("Artist: {}, born {}".format(self.artist,Artist().birth_year))
print("Title: {}, {}".format(self.title,self.year_created))
# TODO: Define print_info() method
if __name__ == "__main__":
user_artist_name = input()
user_birth_year = int(input())
user_death_year = int(input())
user_title = input()
user_year_created = int(input())
user_artist = Artist(user_artist_name, user_birth_year, user_death_year)
new_artwork = Artwork(user_title, user_year_created, user_artist)
new_artwork.print_info()
Enter program input (optional)
Pablo Picasso
1881
1973
Three Musicians
1921
Program errors displayed here
Traceback (most recent call last):
File "main.py", line 16, in <module>
class Artwork:
File "main.py", line 17, in Artwork
def __init__(self,title ="None",year_created = 0, artist=Artist().name):
File "main.py", line 3, in __init__
name = self.name
AttributeError: 'Artist' object has no attribute 'name'
You have the class rules backwords in Artist.init()
Classes work so that:
Class MyClass:
def __init__(name,date):
self.name = name
self.date = date
self.name is the class name that gets assigned the name when initialized so doing the opposite should return None or nothing if I'm correct. Just switch those 2 and then doing:
newClass = MyClass("Pablo","2019")
print(MyClass.name)
print(MyClass.date)
returns:
Pablo
2019
If date is date:str on the init() function then str() the date first.

NameError: name 'self' is not defined - but I think I did it correctly [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 last year.
Improve this question
I just started learning Python from scratch and now I am trying to learn classes concept and can't seem to find why my code is returning an error.
Could you please teach me what I did incorrectly?
class User():
"""A simple database with restaurant information."""
def __init__(self, first_name, last_name, gender, age):
"""Initialize user's name, gender and age info."""
self.first_name = first_name
self.last_name = last_name
self.gender = gender
self.age = age
self.login_attempts = 0
def increment_login_attempts(self):
"""Increments the value of login_attempts by 1"""
self.login_attempts += 1
def reset_login_attempts(self):
"""Resets the value of login_attempts."""
self.login_attempts = 0
user3 = User('mino', 'lee', 'male', 35)
print("\n")
user3.increment_login_attempts()
user3.increment_login_attempts()
print("\nLogin attempted " + str(self.login_attempts) + " times.")
user3.reset_login_attempts()
print("\nLogin attempted " + str(self.login_attempts) + " times.")
"self" only applies if you're in a class method which has a "self" parameter. From the outside, you need to use the object name:
print("\n")
user3.increment_login_attempts()
user3.increment_login_attempts()
print("\nLogin attempted " + str(user3.login_attempts) + " times.")
user3.reset_login_attempts()
print("\nLogin attempted " + str(user3.login_attempts) + " times.")

Problems with multiplying a class variable with an instance

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.

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.

I keep getting error that says main is not defined. I just want it to run. It's supposed to let me enter the description, price, and unit [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 7 years ago.
Improve this question
class RetailItem:
# The _init_ method initalizes the attributes.
def __init__(self, description, units, price):
self.__description = description
self.__units = units
self.__price = price
# The set_description method acccetps an argument for the retailitem's description.
def set_description(self, description):
self.__description = description
# The set_units method accepts an argument for the retailitem's units.
def set_units(self, units):
self.__units = units
# the set_price method accepts an argument for the retailitem's price.
def set_price(self, price):
self.__price = price
# The set_description methods returns the retailitem's description.
def get_description(self):
return self.__description
# The get_units method returns the retailitem's units.
def get_units(self):
return self.__units
# The get_price method returns the retailitem's price.
def get_price(self):
return self.__price
def make_list ():
#Create an empty list
item_list = []
# Add Item Object to the list
print ('Enter date for the items')
keep_going = 'Y'
i = 1
while keep_going.upper() == 'Y':
print('Item n*',i)
#Get the Item data
descript = input('Enter the description: ')
units_Inv = input('Enter the units: ')
prix = float(input('Enter the price:$'))
print()
# Create an instance of the retailitem class
item = retailitem.RetailItem(descript, units_Inv, prix)
i += 1
#Add the Object to the list
item_list.append(item)
keep_going = input('Press Y to continue to add Data for item or N to stop: ')
# return the list
return item_list
def display_list(item_list):
for var in item_list:
print(var.get_description())
print(var.get_units())
print(var.get_price())
print()
#call the main function.
main ()
main needs to be defined (def main doesn't appear in your example, at least). My guess is that you are expecting the following:
def main():
lst = make_list()
display_list(lst)
The problem is exactly what the error message is telling you:
#call the main function.
main ()
Where is main() defined?
This may be caused by confusion about how Python works vs. other languages. In Python, anything at the global level is executed automatically -- it doesn't need to go in a main function.
So, if you want to run some code, just do it:
class RetailItem:
def __init__(self, description, units, price):
self.__description = description
self.__units = units
self.__price = price
# etc.
l = make_list()
display_list(l)
Typically you would wrap that code at the end in a if __name__ == "__main__" block, but it's not required.
you need somewhere
def main():
#function body - whatever you want it to do
in this case, what it looks like you want to do is to create an instance of the RetailItem class and then call its methods.
The error says the issue. "main is not defined".
You are calling the main() function at the end but didn't define it anywhere in the code.
def main():
# this is your main function
list = make_list()
display_list(list)
w.r.t. "I just want it to run": add the following to the top of your code:
def main():
pass
Your code will now run. Technically.
If you want to reference putting all of the functions together you actually need to declare a function called main() EX:
def main():
makelist()
displaylist(item_list)
####################################
main()

Categories

Resources