How do I fix module 'petspgm' has no attribute 'PetData' error? - python

I keep getting this error no matter what I do. Its suppose to make a new data but it does not seem to want to work. The full error is:
line 35, in make_list
pet = petspgm.PetData(pet_name, pet_type, pet_age)
builtins.AttributeError: module 'petspgm' has no attribute 'PetData'
Here's the code for petspgm
class PetData:
# The __init__ method initializes the attributes
def __init__(self, pet_name, pet_type, pet_age):
self.__pet_name = pet_name
self.__pet_type = pet_type
self.__pet_age = pet_age
# This method accepts an argument for the pet's name
def set_pet_name(self, pet_name):
self.__pet_name = pet_name
# This method accepts an argument for the pet's type
def set_pet_type(self, pet_type):
self.__pet_type - pet_type
# This method accepts an argument for pet's age
def set_pet_age(self, pet_age):
self.__pet_age = pet_age
# This method returns the pet's name
def get_pet_name(self):
return self.__pet_name
# This method returns the pet's type
def get_pet_type(self):
return self.__pet_type
# This method returns the pet's age
def get_pet_age(self):
return self.__pet_age
and the code for the other one
import petspgm
def main():
# Get a list of pet objects
pets = make_list()
# Display the data in the list
print ('Here is the data you entered: ')
display_list(pets)
# This function gets data deom rhe user for 3 pets. It returns a list of pet objects containing the data
def make_list():
# Create an empty list
pet_list = []
# Add 3 pet objects to the list
print ('Enter the data for 3 pets')
for count in range(1, 4):
# Get the pet data
print ('Pet number ' + str(count) + ':')
pet_name = input("Enter your pet's name: ")
pet_type = input('Enter the type of pet: ')
pet_age = input("Enter your pet's age: ")
print
# Create a new Pet Data object in memory and assign it to the pet variable
pet = petspgm.PetData(pet_name, pet_type, pet_age)
# Add the object to the list
pet_list.append(pet)
# Return the list
return pet_list
# This function accepts a list containing Pet Data objects as an argument and displays the data stored in each object
def display_list(pet_lists):
for item in pet_list:
print ("Pet's name is: " + item.get_pet_name())
print ("Pet's type is: " + item.get_pet_type())
print ("Pet's age is: " + item.get_pet_age())
# Call the main function
main()
input('Press Enter to continue')
I have tried adding a pet data code but then the entire code crashes and the file wont be able to be opened by python. I have tried using different wording in the coding and it give the same error. I've also just tried to make the list myself but it just crashes python.

Related

Functions homework

My apologies as I am very new to Python and coding in general but I am trying an exercise on creating functions and formatting all in the same. Here I have a function I wrote for practice. But I can't get it to run correctly. What am doing wrong with creating this function.
My code:
def greeting(name):
name = input("What's your name: ")
return "Hi %s" % name
print(greeting())
The error:
TypeError: greeting() missing 1 required positional argument: 'name'
Thank you for your help. :)
You don't need to give name as a parameter to the greeting function.
Try this:
def greeting():
name = input("What's your name: ")
return "Hi %s" % name
print(greeting())
You don't want to take name as an argument, because you are creating that variable within the function in your call to input()
def greeting():
name = input("What's your name: ")
return "Hi %s" % name
You also do not need to print() the function, because it's return value (a string) is printed by default. If you saved the return value of greeting() into an object, you could then print that object
the_greeting = greeting()
print(the_greeting)

Creating a Student class and printing from user input

We were asked to do the following:
Create a class Student with public member variables: Student name, student number, contact number, ID number. The following specifications are required:
Add init() method of the class that initializes string member variables to empty strings and numeric values to 0.
Add the method populate() to the class. The method is used to assign values to the member variables of the class.
Add the method display() to the class. The method is used to display the member variables of the class. (2)
Create an instance StudentObj of the class Student in a main program.
The main program should prompt the user to enter values for five students. The attributes should be assigned to the instance of Student using its populate() method, and must be displayed using the display() method of the instance of Student.
I have created an int function which initialises string variables to empty strings and numeric values to int variables, a populate function which assigns values to variables in the class and a display method to print the values of the class. The main method is supposed to ask the user to input their details and then print these details using the display() method.
class Student:
def __init__(self, student_name, student_num,contact_num,ID_num):
self.student_name = ""
self.student_num = 0
contact_num = 0
ID_num = 0
def populate(self,student_name, student_num,contact_num,ID_num):
self.student_name = student_name
self.student_num = student_num
contact_num = contact_num
ID_num = ID_num
def display(student_name, student_num,contact_num,ID_num):
print(student_name)
print(student_num)
print(contact_num)
print(ID_num)
def main():
StudentObj = Student()
s_name = int(input("Enter student name: "))
s_num = int(input("Enter student number: "))
con_num = int(input("Enter contact number: "))
ID_num = int(input("Enter ID number: "))
populate(s_name,s_num,con_num,ID_num)
display(s_name,s_num,con_num,ID_num)
if __name__ == '__main__':
main()
The program finished with exit code 0, however it does not ask for any inputs or print anything
As #Xteven suggested, call to the main function is missing.
You need
if __name__ == '__main__':
main()

Python, program open and close in 10th of second

Here is my code as follows.
# starting of Employee class
class Employee(object):
def __init__(self): #declaring Constructor
self.name = ""
self.iDnumber = ""
self.department = ""
self.jobTitle = ""
# setter methode for setting values to the class properties
def setName(self,name):
self.name=name
def setIDnumber(self,iDnumber):
self.iDnumber=iDnumber
def setDepartment(self,department):
self.department=department
def setJobTitle(self,jobTitle):
self.jobTitle=jobTitle
# getter methode for getting values of the class properties
def getName(self):
return self.name
def getIDnumber(self):
return self.iDnumber
def getDepartment(self):
return self.department
def getJobTitle(self):
return self.jobTitle
# methode which takes object as an argument and display its properties
def display(emp_object):
print("Name : ",emp_object.getName())
print("IDnumber : ",emp_object.getIDnumber())
print("Department : ",emp_object.getDepartment())
print("JobTitle : ",emp_object.getJobTitle())
# Main methode of the program
if __name__ == "__main__":
employeeList = [] #List to hold the Employee objects
emp1 = Employee()
emp2 = Employee()
emp3 = Employee()
# appending objects to the list
employeeList.append(emp1)
employeeList.append(emp2)
employeeList.append(emp3)
# Initializing each objects of the list
for employee in employeeList:
emp_name = input("Enter your Name ")
employee.setName(emp_name)
emp_iDnumber = input("Enter your iDnumber ")
employee.setIDnumber(emp_iDnumber)
emp_department = input("Enter your Department ")
employee.setDepartment(emp_department)
emp_jobTitle = input("Enter your JobTitle ")
employee.setJobTitle(emp_jobTitle)
# Displaying each objects of the list
for emp_object in employeeList:
display(emp_object)
and, when I run it termianl just flash for a 10th of seconds and do not ask for input.
Help me with this thank you.
I am trying to focus on
Display a message asking user to enter employee name, ID, department, and title
b. Read employee name into a variable
c. Call the set name method of the first object passing the name
d. Read employee ID into a variable
Probably you are running it on windows... Simple add a input() at the end of you main to pause program and prevent windows from close it
And you need to indent your code
if __name__ == "__main__":
employeeList = [] #List to hold the Employee objects
emp1 = Employee()
emp2 = Employee()
emp3 = Employee()
# appending objects to the list
employeeList.append(emp1)
employeeList.append(emp2)
employeeList.append(emp3)
input()

Python Referencing a name of a class object in a function

I've never used classes before and I am trying to get a general understanding of how they work with the code example I have below. Im having issues referencing one of the names i define for a class. i just want the program to print out a list of the employee names and salaries stored in the list when the option 2 is entered but it gives me the following error:
Traceback (most recent call last):
File "C:\Scott Glenn\Misc\classes.py", line 31, in
employees[i].displayEmployee
AttributeError: 'str' object has no attribute 'displayEmployee'
class Employee:
'Common base class for all employees'
empCount = 0
def __init__(self, name, salary):
self.name = name
self.salary = salary
Employee.empCount += 1
def displayCount(self):
print "Total Employee %d" % Employee.empCount
def displayEmployee(self):
print "Name : ", self.name, ", Salary: ", self.salary
def AddNewEmployee():
NewEmployee = raw_input("What is the Employees name: ")
employees.append(str(NewEmployee))
NewEmployeeSalary = raw_input("What is the Employees salary: ")
NewEmployee = Employee(NewEmployee, NewEmployeeSalary)
return employees
#=============================================================================
employees=[]
while(1):
print'Welcome to the Employee Database!'
option = raw_input('Please select 1 to add new employee or 2 to display all current employees: ')
if option=='1':
employees.append(AddNewEmployee())
if option=='2':
for i in range(0,len(employees)):
employees[i].displayEmployee
The AddNewEmployee function is wrong. It's returning a list of a single string when you want to be returning a single object of your custom type Employee.
It should be more like this:
def AddNewEmployee():
#string variable to hold name
NewEmployeeName = raw_input("What is the Employees name: ")
#why make a list? you are appending the result of this function to that list
#employees.append(str(NewEmployee))
#plus this is adding the employee before he's even been created
NewEmployeeSalary = raw_input("What is the Employees salary: ")
#construct using name string and salary string
NewEmployee = Employee(NewEmployeeName, NewEmployeeSalary)
return NewEmployee #return Employee object (to be appended later)
Additionally, you are trying to access displayEmployee() as a field of your class, instead of as a method. Fields don't have parenthesis and methods do (so they can take parameters, though in this case the parenthesis are empty as no parameters are passed).
Finally, note that raw_input returns a string so you should cast to float if that is what you wish your NewEmployeeSalary to be. (Right now it's a string.)
I've updated your code below. The main issue that I saw that you had was that you were using 'employees' as a global and appending to it twice. I moved it out of the AddNewEmployee() function and had that return the new employee which is then appended to 'employees'
Also you weren't calling '.displayEmployees'
Notice the the parentheses that I added to the end.
I hope this helps!
class Employee(object):
'Common base class for all employees'
empCount = 0
def __init__(self, name, salary):
self.name = name
self.salary = salary
Employee.empCount += 1
def displayCount(self):
print "Total Employee %d" % Employee.empCount
def displayEmployee(self):
print "Name : ", self.name, ", Salary: ", self.salary
def AddNewEmployee():
NewEmployee = raw_input("What is the Employees name: ")
NewEmployeeSalary = raw_input("What is the Employees salary: ")
NewEmployee = Employee(NewEmployee, NewEmployeeSalary)
return NewEmployee
# =============================================================================
if __name__ == "__main__":
employees = []
while True:
print'Welcome to the Employee Database!'
option = raw_input(
'Please select 1 to add new employee or 2 to display all current employees: ')
if option == '1':
employees.append(AddNewEmployee())
if option == '2':
for i in range(0, len(employees)):
employees[i].displayEmployee()

Trying to use random numbers to generate an outcome for Class module

I am having trouble returning to __mood field to generate a random mood for the animal objects. I don't know how to make it work, so what I have been trying to do is define it in the program titled animals.py
I have two programs: animals.py and animalgenerator.py
The animal generator asks for user input and produces a list that looks like:
What type of animal would you like to create? Truman
What is the animal's name? Tiger
Would you like to add more animals (y/n)? n
Animal List
-----------
Tiger the Truman is hungry
So far my program has worked, but it won't produce the moods.
__mood is a hidden attribute for the animal object.
check_mood: this method should generate a random number between 1
and 3.
The random number will be used to set one of three moods:
If the number is 1, the __mood field should be set to a value of “happy”.
If the number is 2, the __mood field should be set to a value of “hungry”.
If the number is 3, the __mood field should be set to a value of “sleepy”.
Finally, this method should return the value of the __mood field
Here is what I have on animals.py
class Animal:
# The __init__ method initializes the attributes
def __init__(self, name, mood, type):
self.__name = name
self.__mood = mood
self.__animal_type = type
def _animal_type(self, type):
self.__animal_type = type
def __name(self, name):
self.__name = name
def __mood(self, mood):
for i in range():
if random.randint(1, 3) == 1:
self.__mood = 'happy'
if random.randint(1, 3) == 2:
self.__mood = 'hungry'
if random.randint(1, 3) == 3:
self.__mood = 'sleepy'
else:
self.__mood = 'happy'
def get_animal_type(self):
return self.__animal_type
def get_name(self):
return self.__name
def check_mood(self):
return self.__mood
Here is what I have for animalgenerator.py
# This program tests the Animal class.
import animals
print("Welcome to the animal generator!")
print("This program creates Animal objects.")
def main():
# Get the animal data
animal_list = []
find_info = True
while(find_info):
_animal_type = input('\nWhat type of animal would you like to create? ')
__name = input('What is the animals name? ')
more_animals = input('Would you like to add more animals (y/n)? ')
if (more_animals != 'y'):
find_info = False
# Create an instance of animal class
animal_list.append(animals.Animal(_animal_type, __name, __mood))
animal = animals.Animal(_animal_type, __name, __mood)
# Display the data that was entered.
print('\nAnimal List\n')
print('------------- \n')
for animal in animal_list:
print('' + animal.get_animal_type() + ' the ' + animal.get_name() + ' is ' + animal.check_mood() + '\n')
# Call the main function
main()
A couple of thoughts: First, in __mood you have for i in range(): but range requires at least 1 argument. I think you probably don't want that at all, since there's no reason to be looping there that I can see.
Second, you probably need not generate a new random number for each check. If you generate the random int from 1 to 3 a single time and see if it's 1, 2, or 3 you should be able to set the mood you want.
Third, check_mood doesn't ever call __mood to have it generate set a new mood. Also, the way I read your assignment, er, requirements, you're supposed to generate the random number in check_mood then pass it to __mood instead of generating it within.
Forth, and probably more important than many of the above, particularly the third point, __mood can't be both a method name and attribute name. Probably you don't want __mood to be a method and just have the body of it in check_mood.
I believe this method can be written elegantly in 1-2 lines:
def __setmood(self):
self.__mood = ('happy', 'hungry', 'sleepy')[random.randint(0, 2)]
return self.__mood
But aside from that, I don't think you should use the same name for your method and your instance variable. When you do an assignment like self.__mood = 'happy', you actually overwrite the binding to the method of your object. In other words, you can't call the self.__mood() method anymore even from within the class...
For example, the following code will raise a TypeError ('str' object is not callable):
class X:
def __mood(self):
self.__mood = 'happy'
def callmood(self):
self.__mood()
return self
X().callmood().callmood()

Categories