I'm working with Inheritance in python but i'm getting an error i don't know how to fix, 'finalStore' object has no attribute 'marone'. I get this when i try create an object.
from ClassFile import studStore
class finalStore (studStore):
grandAve = 0
numStu = 0
def __init__(self, name, marone, martwo, marthree, marfour, corone, cortwo, corthree, corfour):
studStore.__init__(self, name, marone, martwo, marthree, marfour)
self.corone = corone
self.cortwo = cortwo
self.corthree = corthree
self.corfour = corfour
finalStore.numStu += 1
self.holder = finalStore.numStu
self.average = (marone + martwo + marthree + marfour)/4
finalStore.grandAve += self.average
self.storit = finalStore.grandAve
My initializing for the child class
class studStore:
def __init__(self, name, marone, martwo, marthree, marfour):
self.newname = name
self.Ave = 0
self.marone = marone
self.martwo = martwo
self.marthree = marthree
self.marfour = marfour
And the initializing for the parent class. My main line is just a loop where i create multiple objects for but it errors on this line:
listIn.append(finalStore(name, gradeone, gradetwo, gradethree, gradefour, courseOne, courseTwo, courseThree, courseFour))
I'm not sure what the error is but I have a similar program that works, I'm just not using the from * import *
I'm outputting it like this
for i in range (0,len(listIn)):
print(str(listIn[i].returnName()).ljust(20," "), end = " ")
print(str(listIn[i].returnOne()).ljust(20, " "))
print(str(listIn[i].returnTwo()).ljust(20, " "))
print(str(listIn[i].returnThree()).ljust(20, " "))
print(str(listIn[i].returnFour()).ljust(20, " "))
Your call to the super class's init function is incorrect. Here is how you should do it:
class finalStore(studStore):
def __init__(self, name, ...):
super(finalStore, self).__init__(name, marone, ...)
Related
I've tried many different things so it's a little all over the place, please help
I've been able to make the first class and then in a different file create some objects for it, but for this subclass I need to use user input and I just can't figure it out.
I have made it so the shift input has to be a 1 or 2 for a day or night shift, I just don't have the knowledge for this.
class Employee:
def __init__(self, name, id, dept, title):
self.__name = name
self.__id = id
self.__dept = dept
self.__title = title
def get_name(self):
return self.__name
def get_id(self):
return self.__id
def get_dept(self):
return self.__dept
def get_title(self):
return self.__title
def __str__(self):
result = ""
result += "Name: " + self.get_name() + "\tID Number: " + str(self.get_id()) + \
"\tDepartment: " + self.get_dept() + "\tJob Title:" + self.get_title()
return result
class ShiftEmployee(Employee):
def __init__(self, name, id, dept, title, shift, pay):
Employee.__init__(self, name, id, dept, title)
self.__shift = shift
self.__pay = pay
#classmethod
def inputs(self):
self.__name = input("Enter name: ")
self.__id = input("Enter ID number: ")
self.__dept = input("Enter department: ")
self.__title = input("Enter Jobe title: ")
self.__shift = input("Enter shift: ")
self.__pay = input("Enter hourly pay: ")
#set_shift(self, shift):
#self.__shift = shift
#def set_pay(self, pay):
#self.__pay = pay
def get_shift(self, shift):
if self.__shift == 1:
return "Day"
elif self.__shift == 0:
return "Night"
else:
return "Invalid entry"
def get_pay(self, pay):
return self.__pay
def __str__(self):
result = ""
#result += Employee.__str__(self)
result += "Name: " + self.get_name(ShiftEmployee) + "\tID Number: " + str(self.get_id(ShiftEmployee)) + \
"\tDepartment: " + self.get_dept(ShiftEmployee) + "\tJob Title:" + self.get_title(ShiftEmployee) + \
"\tShift: " + self.get_shift(ShiftEmployee) + "\tHourly Pay: " + str(self.get_pay(ShiftEmployee))
return result
shift_emp = ShiftEmployee
shift_emp.inputs()
print(shift_emp.__str__(ShiftEmployee))
Don't use a classmethod because
A class method is a method that’s shared among all objects.
Though python itself does not force this behavior, your use of self in the inputs definition indicates that you are not doing what you think. the parameter is traditionally named cls in #classmethod-annotated methods, because the object you're referring to inside the body is not an instance of the class, but the class object itself. This means if you have multiple ShiftEmployee objects, they're going to be writing their data to the same variables. This is not what you want to happen.
you are not instantiating a ShiftEmployee object with shift_emp = ShiftEmployee, but rather assigning the class to the variable shift_emp, which is not what you want to do. so if you remove the #classmethod annotation, I think what you want is
shift_emp = ShiftEmployee() # __init__ gets called when you use this constructor invocation
shift_emp.inputs()
print(shift_emp)
Your __str__ methods don't make a lot of sense. You are passing the class object to each getter, which doesn't seem like it's what you'd want to do. The class object defines the class, what you want are the instances of the class. It's an important, if initially confusing distinction. Posting the error you get would help, but here's what I would expect the methods to look like. I'm not using the getters, because this is internal access, but you can use them instead of directly referring to the state variables if you prefer.
# Employee
def __str__(self):
return f"Name: {self.__name} ID Number: {self.__id} Department: {self.__dept} Job Title: {self.__title}"
# ShiftEmployee
def __str__(self):
return super(ShiftEmployee, self).__str__() + f" Shift: {self.__shift} Hourly Pay: {self.__pay}"
So what's going on here? For one thing, we use format strings because they are easier to work with and exactly the thing you wanted. Then we're using the superclass (Employee) to provide the shared functionality, and using the descendent class to enrich with the ShiftEmployee-only data. I skipped the accessor methods because they're redundant when accessing "private" data from inside the class members. Note that this won't quite do what you expect, either, w.r.t. the shift value that gets printed -- it's going to print the int, not "Night" or "Day". This is where your accessor method comes into play, except that your accessor has an extraneous parameter, shift. So you'd have to remove that value.
Please use the following way to initialize the class and printing the class,
shift_emp = ShiftEmployee() # Added Parenthesis
shift_emp.inputs()
print(str(shift_emp)) # Pass class object to inbuilt str() method to get output from __str__() method from class
I had an assignment to create a python code using class to create a group with 3 members (aggregation relationship). This is my code so far:
class Member:
def __init__(self,name,age):
self.name = name
self.age = age
def getInfo(self):
memberInfo = "Name: " + str(self.name) + "." + "Age: " + str(self.age)
return memberInfo
class Group:
def __init__(self,name):
self.name = name
self.memlist = []
def addMember(self,member):
self.memlist.append(member)
def getInfo(self):
info = "Member List: \n"
for i in range(len(self.memlist)):
info += self.memlist[i].getInfo() + "\n"
print(info)
break
mem1 = Member("Chi",20)
mem2 = Member("Bach",7)
mem3 = Member("Gen", 22)
group1 = Group("Siblings")
group1.addMember(mem1)
group1.addMember(mem2)
print(group1.getInfo())
print(mem2.getInfo())
print(group1.memList)
But it has shown an error: AttributeError: 'Group' object has no attribute 'memList'. Is there anything I can do to fix this?
I wrote little function for listing members and their ages.
class member:
def __init__(self, name, age):
self.name = name
self.age = age
def member_Info(self):
memberInfo = f"Name: {str(self.name)}-->Age: {str(self.age)}"
return memberInfo
class Group:
def __init__(self, name):
self.name = name
self.memlist = []
def addMember(self, name):
self.memlist.append(name)
def getInfo(self):
for i in range(len(self.memlist)):
info = self.memlist[i].member_Info() + "\n"
print(info)
This all_members function is basically getting the information stored in the member class and return to list. I print using memlist in Group but it didn't work out so I made a new list using all_member function and get information from memlist in group1 with the code that you used for getting information in memlist at group1.getInfo .
def all_members():
all_mems = []
for i in range(len(group1.memlist)):
all_mems.append(group1.memlist[i].member_Info())
print(all_mems)
mem1 = member("Chi", "20")
mem2 = member("Bach", "7")
mem3 = member("Gen", "22")
group1 = Group("Siblings")
group1.addMember(mem1)
group1.addMember(mem2)
group1.addMember(mem3)
print(group1.getInfo())
print(mem2.member_Info() + "\n")
print(all_members())
I guess this isn't the best answer you can get but I think it will work and also I learn many things while trying to correct it so thank you for posting that.
change
print(group1.memList)
to
print(group1.memlist)
I have the following error when I run this program: NameError: name create is not defined. I`m trying to creeate a library program to add/remove/see all the books and everything will be stored in a .dat file
I defined the function, but I'm not sure why it's not working. I copied the code below:
import pickle
import os
class Library:
def __init__(self,book ,title,author,pubdate,status,retdate,location):
self.book = book
self.title = title
self.author = author
self.pubdate = pubdate
self.status = status
self.retdate = retdate
self.location = location
def details(self):
self.details = " Title: " + self.title + " Author: " + self.author + " Publication date: " + str(self.pubdate) + " Status" + self.status + " Return date : " + str(self.retdate) + "location" + str(self.location)
print(self.details)
def create(self):
harvard_lib = Library(self.title, self.author, self.pubdate, self.status, self.retdate, self.location)
self.location = 1
while index !="Q" :
book = str(input("Book:"))
title = str(input("Enter the title of the book: "))
author = str(input("Enter the author of the book: "))
pubdate = int(input("Enter the publication date of the book: "))
status = str(input("Enter the status of the book(A / N): ")) # a-available, n- not
retdate = int(input("Enter the return date of the book: "))
index = str(input("Press any key to continue,or pres Q to quit"))
location +=1
booklist = 'booklist.dat'
newitem = []
if os.path.exists(booklist):
with open(booklist,'rb') as rfp:
newitem = pickle.load(rfp)
newitem1 = book,title,author,pubdate,status,retdate,index,location
newitem.append(newitem1)
with open(booklist,'wb') as wfp:
pickle.dump(newitem, wfp)
with open(booklist,'rb') as rfp:
newitem = pickle.load(rfp)
print(newitem)
harvard_lib.create()
create() is a method of Library class, not a function.
If you want to access a method of a class, you need an instance of that class.
Try something like that:
harvard_lib = Library("bookname", "title", ...)
harvard_lib.create()
You need to create an instance of the class first before you can make use of that method. It is a method of a class so you should not treat it as a normal function.
hash_lib = Library("Lord of the Rings","J.R Tolkien",...) #creating a class instance
hash_lib.create() #making use of the class method
with this you should be good to go
I have two different devices I use in the lab. I would like to use input from command line to change which device I am using. To elaborate, I would like to type in the name of the device and a variable is defined by that name inside a if statement. Currently when I try the below code I get:
AttributeError: class temp_class has no attribute 'get_int'
What am I doing wrong
from classA import*
from classB import*
from temp_class import*
tempC = temp_class()
print tempC
user_input = raw_input()
print user_input
if (user_input == "a") :
tempC.__del__()
tempC = class_a(5)
if (user_input == 'b') :
tempC = class_b(5)
print temp_class
tempC.set_int(5)
print temp_class.get_int()
Output of code:
What is inside temp_class
class temp_class:
def __init__(self):
self.num = 8
What is inside classA
class class_a(object):
def __init__(self, int):
self.num = self.set_int(int)
def set_int(self, int):
self.num = int
def get_int(self):
return self.num
what is inside class_b
class class_b:
def __init__(self):
self.num = 8
There is a lot of trouble with the code you've shared. I'll try to simplify it:
# prog.py
from device_a import DeviceA
from device_b import DeviceB
user_input = raw_input() # use input() if you have python3
if (user_input == "a") :
# no need to create an initial "temp" instance or to delete it
tempC = DeviceA(5)
elif (user_input == 'b') :
tempC = DeviceB() # DeviceB doesn't take any parameters
# tempC can either be a DeviceA or DeviceB, but both need to have the same methods defined
try:
tempC.set_int(5) # this will fail for DeviceB because it has no set_int method
except: # this should have a more specific exception type
pass
print tempC.get_int() # note that this is the name of the variable, not the class
# device.py
class Device(object):
def __init__(self, num):
self.num = num
def get_int(self):
return self.num
# device_a.py
from device import Device
class DeviceA(Device):
def __init__(self, num): # int is a builtin function, so it shouldn't be used as a parameter name
super(DeviceA, self).__init__(num)
def set_int(self, num):
self.num = num
# device_b.py
from device import Device
class DeviceB(Device):
def __init__(self):
super(DeviceB, self).__init__(8)
# no set_int, as this one seems to be fixed in your example
Last night I figure out how to fix my problem. Below is what I am now using.
obj_dic = {}
print obj_dic
print("a for class a for class b")
user_input = raw_input(":> ")
if user_input == 'a':
obj_dic = {'a':class_a()}
else:
obj_dic = {'b':class_b()}
tempC = obj_dic.get(user_input)
print tempC.get_int()
print tempC
I am working on a small module.
I have a class called pricelist. It contains the attributes prefix and price.
class pricelist:
def setPrefix(self,prefix):
self.prefix = prefix
def setPrice(self,price):
self.price = price
def getPrefix(self):
return self.prefix
def getPrice(self):
return self.price
def getPrefixLength(self):
return len(self.prefix)
I have created a list of pricelist objects.
now i want to perform the operation, where when i give a phone number as input, i want to find prefix of the number and the corresponding price related to the prefix.
Example:
prefix price
46 2.0
44 3.0
.
.
.
.
when i give the input say "46 7223232323", it should return the price corresponding to it.
I am new to python and python classess, so can you please help me out with the logic of this
Keep the prefixes and prices in a dict:
self.data = {"46": 2.0,"44":3.0}
inp = "46 7223232323"
get_pre = inp.split()[0]
print (self.data.get(get_pre))
2.0
class Pricelist:
def __init__(self):
self.data = {"46": 2.0,"44":3.0}
p = Price_list()
inp = "46 7223232323"
get_pre = inp.split()[0]
print (p.data.get(get_pre,"Sorry that is an invalid prefix")) # if the prefix does not exist, it will output "Sorry that is an invalid prefix"
You can access attributes directly without getters and setters:
class Price_list:
def __init__(self,prefix,price):
self.prefix = prefix
self.price = price
self.pre_len = len(self.prefix)
p = Price_list("46", "4.99")
print (p.prefix, p.price, p.pre_len)
You can use data as a class attribute and add all instance attributes to it:
class Price_list:
data = {}
def __init__(self, prefix, price):
self.prefix = prefix
self.price = price
self.pre_len = len(self.prefix)
p = Price_list("46", "4.99")
p.data[p.prefix] = [p.price]
p1 = Price_list("44", "3.99")
p1.data[p1.prefix] = [p1.price]