append data to constructor empty list variable in python - python

I have one class. For that i want to append data to constructor empty list variable. I am trying to append data. But it's not working and throwing error as "NameError: name 'items' is not defined". before this code has been worked.
Here it my code snippet :
class data:
def __init__(self,items=[]):
self.items = items
self.m1(n)
def m1(self,n):
self.n=2
for i in range(self.n):
d = input('enter the values :')
self.items.append(d)
print(self.items)
d=data(items)

here are some issues wrong:
1.) On line 11, items is not defined anywhere before trying to initialize the class, so you end up receiving an error when you call
d=data(items)
2.) On line 4, n is not defined. It is neither passed in along as a parameter with the constructor or defined elsewhere within the constructor block. You will need to define n.
Here is a working version though, with all the variables properly defined:
class data:
def __init__(self, n, items=[]):
self.items = items
self.m1(n)
def m1(self, n):
self.n=2
for i in range(self.n):
d = input('enter the values :')
self.items.append(d)
print(self.items)
items = [1, 5, 7]
d = data(2, items)

class data:
def __init__(self,number,name,list_values=[]):
self.number = int(input('Enter a number :'))
self.name = name
self.list_values = list_values
self.m1()
def m1(self):
for i in range(self.number):
items = input('Enter the values :')
self.list_values.append(items)
print(self.list_values)
list_values= None
d=data('siddarth',list_values)

Related

How to set up constructor for class with attribute initialized to empty list?

I have to create the following class, but I am unsure of how to set up my constructor.
A GradeRecords object has the following attributes:
term : a string representing the current semester;
grades : a list object containing tuples, where the first entry of each tuple is a string representing the code of the class, the second entry of each tuple is the grade out of 100, and the third entry is the number of credits for this course. grades can be initialized as an empty list.
num_courses : an int which contains the number of courses in the record.
This can be initialized as 0.
You are not allowed to add more attributes.
Furthermore, a GradeRecords object has the following methods:
an initialization method which takes as input the current term and initializes the three attributes;
add_course, a method which takes a string representing the course code, an int for the grade out of 100 and the number of credits. The method adds a new tuple to grades.
My code give me the error:
g1 = GradeRecords("Fall 2021")
TypeError: __init__() missing 1 required positional argument: 'new_tuple'
Thank you!
class GradeRecords:
grades = []
num_courses = 0
def __init__(self, term, new_tuple):
self.term = term
#create a list from the input new_tuple
self.grades.append(new_tuple)
GradeRecords.num_courses += len(self.grades)
def add_course(self, course_code, grade_100, num_credits):
new_tuple = (course_code, grade_100, num_credits)
self.grades.append(new_tuple)
return grades
The __init__ of your class has two arguments : term and new_tuple.
When you make an instance of your class as g1 = GradeRecords("Fall 2021"), you give a value for term (="Fall 2021") but the object is waiting for a new_tuple as well.
So to make it works, you should give a tuple as a second argument like :
g1 = GradeRecords("Fall 2021", ("Maths", 90, 10))
However, in my opinion, the class might also be written this way :
class GradeRecords:
def __init__(self, term):
self.grades = []
self.num_courses = 0
self.term = term
def add_course(self, course_code, grade_100, num_credits):
self.grades.append((course_code, grade_100, num_credits))
self.num_courses += len(self.grades)
return self.grades
And we can use it like so :
>>> g1 = GradeRecords('Fall 2021')
>>> g1.add_course("Maths", 90, 10)
[("Maths", 90, 10)]
>>> g1.add_course("Physics", 80, 9)
[('Maths', 90, 10), ('Physics', 80, 9)]
Your __init__ expects 2 arguments while only 1 is passed to it, so you can add a default value to new_tuple if nothing is passed and can be called as g1 = GradeRecords("Fall 2021"). If you want it to be initialised to something else then it can be called as g1 = GradeRecords("Fall 2021", ("Course", "<Grade>", "<Credits>"))
class GradeRecords:
grades = []
num_courses = 0
def __init__(self, term, new_tuple=("",0,0)):
self.term = term
#create a list from the input new_tuple
self.grades.append(new_tuple)
self.num_courses += len(self.grades)
def add_course(self, course_code, grade_100, num_credits):
new_tuple = (course_code, grade_100, num_credits)
self.grades.append(new_tuple)
return grades

Can you take in a function as a parameter for a method in another class?

def hourlylist():
newlist = []
for Employee in employeeobject():
if Employee.classification == "1":
newlist.append(Employee.hourly)
return newlist
class Hourly(Classification): #classification is parent class
def __init__(self,rate,hourly): #list of hours worked
self.hourly = hourly
self.rate = rate
def set_pay(hourlylist()): #hoursworked as parameter
print(hourlylist())
So I have this list from the function hourly list at the top. What I am trying to do is take in the function as a parameter for my set_pay method. Is this possible? Would I be able to call that function in the set_pay method as a parameter and call it inside of the method?
Thanks
def hourlylist():
newlist = []
for Employee in employeeobject():
if Employee.classification == "1":
newlist.append(Employee.hourly)
return newlist
class Hourly(Classification): #classification is parent class
def __init__(self,rate,hourly): #list of hours worked
self.hourly = hourly
self.rate = rate
def set_pay(hourlylist): #hoursworked as parameter
print(hourlylist)
but this will print the code for hourlylist if you want to execute why you are taking it as a parameter simply run it like below
def hourlylist():
newlist = []
for Employee in employeeobject():
if Employee.classification == "1":
newlist.append(Employee.hourly)
return newlist
class Hourly(Classification): #classification is parent class
def __init__(self,rate,hourly): #list of hours worked
self.hourly = hourly
self.rate = rate
def set_pay(self): #hoursworked as parameter
newlist = hourlylist() # to get newlist from function
make sure the hourlylist is defined before this class

dynamic instances of a class object overwriting each other

I have a simple class that stores simple data. The class is as follows.
class DataFormater:
def __init__(self, N, P, K, price):
self.N = N
self.P = P
self.K = K
self.price = price
The code that calls this class is
from DataFormater import DataFormater
#global variables
ObjectList = [0,1,2,3,4,5,6,7,8,9,10,
11,12,13,14,15,16,17,18,19,20,
21,22,23,24,25,26,27,28,29,30,
31,32,33,34,35,36,37,38,39,40,
41,42,43,44,45,46,47,48,49,50]
ObjectListCounter = 0
# main
print "enter you N-P-K values, followed by a coma, then the price"
print "example ----> 5 5 5 %50 "
print "return as many values as you want to sort, then enter, 'done!' when done."
while True:
RawData = raw_input()
if RawData == 'done!':
break
else:
ObjectList[ObjectListCounter] = DataFormater
ObjectList[ObjectListCounter].N = int(RawData[0])
# very simple test way of putting first indice in ObjectList[ObjectListCounter].N
ObjectListCounter += 1
print ObjectList[0].N
print ObjectList[1].N
My idea is that ObjectList[0] would create that object '1' that I could call with 1.N
But, when I call these, it seems that I have overwritten the previous instances.
this is what prints...
return as many values as you want to sort, then enter, 'done!' when done.
12
1
done!
1
1
Thanks so much! And I know that my post is messy, I don't exactly know how to make it more "pretty"
So, it looks like you are assigning the actual class (instead of an instance of the class) in your loop. Where you do this:
ObjectList[ObjectListCounter] = DataFormater
I think what you actually want is this
ObjectList[ObjectListCounter] = DataFormater(...insert args here....)
EDIT to address the comments:
Your class init method looks like this:
def __init__(self, N, P, K, price):
That means that to create an instance of your class, it would look like this:
my_formater = DataFormater(1, 2, 3, 4)
You would then be able to access my_formater.N which would have a value of 1.
What you are trying to do instead is access a CLASS level attribute, DataFormater.N. This is generally used in situations where you have a constant variable that does not change between instances of the class. For example:
class DataFormater():
CONSTANT_THING = 'my thing that is always the same for every instance'
You would then be able to access that variable directly from the class, like this:
DataFormater.CONSTANT_THING
I hope that clears things up.

python - Calling function within same Class

Please see the sample code:
a = [1,2,3,4,5] # main list
b = [4,5,6] #variable list nr1
c = [1,2] #variable list nr2
class union(object):
def __init__(self, name):
self.name = name
def common_numbers(self, variable_list):
self.variable_list = variable_list
for x in self.name:
if x in self.variable_list:
yield(x)
def odd_numbers(self, odds):
self.odds = odds
for x in self.variable_list:
if not x % 2 == 0:
yield x
''' I receive: builtins.AttributeError: 'union' object has no attribute 'variable_list'.'''
x = union(a)
print(list(x.odd_numbers(c)))
I am trying to understand how to call other function within same class. As you can see, I am trying to find odd numbers from common_numbers function.
Please understand this is sample work. I know there are plenty of solutions with or withouth using classes to get propriet result. But in this case, I don't need result, I would really appretiate if you could help me understand the calling other function within class. Sorry for my English and Thank you in advance.
You're getting the error because you never actually define self.variable_list. It's only defined once you call common_numbers(), but you never do that. You can define it when initiating:
class union(object):
def __init__(self, name, variable_list):
self.name = name
self.variable_list = variable_list
def common_numbers(self):
for x in self.name:
if x in self.variable_list:
yield(x)
x = union(a, b)
print list(x.odd_numbers(c))
or after initiating, but before calling odd_numbers:
class union(object):
def __init__(self, name):
self.name = name
def common_numbers(self):
for x in self.name:
if x in self.variable_list:
yield(x)
x = union(a)
x.variable_list = b
print list(x.odd_numbers(c))

Python: referencing class object list of lists

I am fairly new to python. I have tried to define a class, I then want to create an instance from a file, then refer to specific pieces of it, but cannot seem to. This is Python 3.3.0
Here's the class....
class Teams():
def __init__(self, ID = None, Team = None, R = None, W = None, L = None):
self._items = [ [] for i in range(5) ]
self.Count = 0
def addTeam(self, ID, Team, R=None, W = 0, L = 0):
self._items[0].append(ID)
self._items[1].append(Team)
self._items[2].append(R)
self._items[3].append(W)
self._items[4].append(L)
self.Count += 1
def addTeamsFromFile(self, filename):
inputFile = open(filename, 'r')
for line in inputFile:
words = line.split(',')
self.addTeam(words[0], words[1], words[2], words[3], words[4])
def __len__(self):
return self.Count
Here's the code in Main
startFileName = 'file_test.txt'
filename = startFileName
###########
myTestData = Teams()
myTestData.addTeamsFromFile(startFileName)
sample data in file
100,AAAA,106,5,0
200,BBBB,88,3,2
300,CCCC,45,1,4
400,DDDD,67,3,2
500,EEEE,90,4,1
I think I am good to here (not 100% sure), but now how do I reference this data to see... am i not creating the class correctly? How do I see if one instance is larger than another...
ie, myTestData[2][2] > myTestData[3][2] <----- this is where I get confused, as this doesn't work
Why don't you create a Team class like this :
class Team():
def __init__(self, ID, Team, R=None, W = 0, L = 0)
# set up fields here
Then in Teams
class Teams():
def __init__(self):
self._teams = []
def addTeam (self, ID, Team, R=None, W = 0, L = 0)
team = Team (ID, Team, R=None, W = 0, L = 0)
self._teams.append (team)
Now If i got it right you want to overwrite the > operator's behaviour.
To do that overload __gt__(self, other) [link]
So it will be
class Team ():
# init code from above for Team
def __gt__ (self, otherTeam):
return self.ID > otherTeam.ID # for example
Also be sure to convert those strings to numbers because you compare strings not numbers. Use int function for that.
The immediate problem you're running into is that your code to access the team data doesn't account for your myTestData value being an object rather than a list. You can fix it by doing:
myTestData._items[2][2] > myTestData._items[3][2]
Though, if you plan on doing that much, I'd suggest renaming _items to something that's obviously supposed to be public. You might also want to make the addTeamsFromFile method convert some of the values it reads to integers (rather than leaving them as strings) before passing them to the addTeam method.
An alternative would be to make your Teams class support direct member access. You can do that by creating a method named __getitem__ (and __setitem__ if you want to be able to assign values directly). Something like:
def __getitem__(self, index):
return self._items[index]
#Aleksandar's answer about making a class for the team data items is also a good one. In fact, it might be more useful to have a class for the individual teams than it is to have a class containing several. You could replace the Teams class with a list of Team instances. It depends on what you're going to be doing with it I guess.

Categories