python - Calling function within same Class - python

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))

Related

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

append data to constructor empty list variable in 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)

Passing a variable into a class to determine which method to use

im not sure what im missing but it says that my class variable (var1) is not defined
Class Example(var1):
if var1 ==1:
def func1(var2)
x = cursor.execute("SELECT * FROM examples WHERE Name = 'var2' ")
Return x
else pass:
Example(1).func1("example")
could be because im tired and its simple but im also kinda new to this. Any help would be great and thank you
The syntax Class Example(var1): means that you are creating a class, wich inherits from var1. If you want to define a function, use def Example(var1):
Your Syntax is very messed up, lost of mistakes, but cleaned up it would look like this:
class Example():
def __init__(self,var1):
if var1 ==1:
def func1(var2):
x = cursor.execute("SELECT * FROM examples WHERE Name = 'var2' ")
print(var2)
return x
else:
pass
#Example(1).func1("example") you can not call 'func1'. At this point it doesnt exists!!
example = Example(1)
Here is the modular way of achieving the result,
class Example():
def __init__(self, var):
self.var = var
def func(self):
if self.var == 1:
return cursor.execute("SELECT * FROM examples WHERE Name = 'var1' ")
elif self.var == 2:
return cursor.execute("SELECT * FROM examples WHERE Name = 'var2' ")
else:
pass
ex = Example(1)
# call func which automatically executes query based on value of var
ex.func()

using inheritance and calling in other class

code:
class aa:
def getDis():
return 0
class bb(aa):
def getDis():
return 10
class cc(aa):
def getDis():
return 15
class d:
def __init__(self,cust):
self.cust = cust
self.memberLevel = aa()
def cgl(self,amt):
if amt ==1:
self.memberLevel = bb()
elif amt ==2:
self.memberLevel = cc()
else:
self.memberLevel = aa()
Well i have these four classes. What i am trying to do is that in my top three classes i have inheritance. In my class d i am trying to call the respective method if the amount is 1 0r 2 . Instead it is giving me this output:
d1 = d('one')
d1.cgl(1)
print(d1.memberLevel)
output:
<__main__.bb object at 0x036D7BF0>
So help required that how can i use overriding technique.
It seems you were hoping to see the console output:10
Because d1.memberLevel is the bb class itself (not the value 10, and not the function that returns the value 10), the console output shows <__main__.bb object at 0x036D7BF0>. This is correct behavior when printing an object directly.
Perhaps your last line of console code should say:
print(d1.memberLevel.getDis())
Another option would be to assign the value within the "d" class:
self.memberLevel = bb().getDis()
And the member methods require "self", e.g.:
def getDis(self):
return 10

python unbound method again

This gets me into difficult time (sorry, i am still very new to python)
Thank you for any kind of help.
The error
print Student.MostFrequent() TypeError: unbound method
MostFrequent() must be called with
Student instance as first argument
(got nothing instead)
This Student.MostFrequent() is called all the way in the end (last line) and the def is last def in the class
EDITED - Naming convention
My long code
import csv
class Student:
sports = []
ftopics = []
stopics = []
choice_list = []
choice_dict = {}
def __init__(self, row):
self.lname, self.fname, self.ID, self.gender, self.sport, self.movie, self.movieyr, self.country, self.ftopic, self.stopic = row
self.sports.append(self.sport)
self.ftopics.append(self.ftopic)
self.stopics.append(self.stopic)
def print_information(self):
return (self.lname, self.fname, self.ID, self.gender)
def print_first(self):
return (self.lname, self.fname, self.sport)
def print_second(self):
return (self.lname, self.fname, self.movie, self.movieyr)
def print_third(self):
return (self.lname, self.fname, self.country)
def print_fourth(self):
return (self.lname, self.fname, self.ftopic, self.stopic)
def most_frequent(self):
for choice in self.choice_list:
self.choice_dict[choice] = self.choice_dict.get(choice, 0) + 1
self.mostFrequent = sorted([(v, k) for k, v in self.choice_dict.items()], reverse=True)
print self.mostFrequent
reader = csv.reader(open('new_mondy_csc_data_revise.csv'), delimiter=',', quotechar='"')
header = tuple(reader.next())
print "%-17s|%-10s|%-6s|%s" %header[:4]
print "-" * 45
students = list(map(Student, reader)) # read all remaining lines
for student in students:
print "%-17s|%-10s|%-6s|%3s" % student.print_information()
print "%-17s|%-10s|%s" %(header[0],header[1],header[4])
print "-" * 45
for student in students:
print "%-17s|%-10s|%s" %student.print_first()
print "%-17s|%-10s|%-16s|%s" %(header[0],header[1],header[5],header[6])
print "-" * 45
for student in students:
print "%-17s|%-10s|%-16s|%s" % student.print_second()
print "%-17s|%-10s|%s" %(header[0],header[1],header[7])
print "-" * 45
for student in students:
print "%-17s|%-10s|%s" %student.print_third()
print "%-17s|%-10s|%-15s|%s" %(header[0],header[1],header[8],header[9])
print "-" * 45
for student in students:
print "%-17s|%-10s|%-16s|%s" % student.print_fourth()
k = len(students)
# Printing all sports that are specified by students
for s in set(Student.sports): # class attribute
print s, Student.sports.count(s), round(((float(Student.sports.count(s)) / k) *100),1)
# Printing sports that are not picked
allsports = ['Basketball','Football','Other','Baseball','Handball','Soccer','Volleyball','I do not like sport']
allsports.sort()
for s in set(allsports) - set(Student.sports):
print s, 0, '0%'
Student.choice_list = Student.sports
X = Student()
X.most_frequent()
#class Search(Student):
# def __init__(self):
# Student.__init__
first read PEP-8 on naming conventions:
Method Names and Instance Variables
Use the function naming rules: lowercase with words separated by
underscores as necessary to improve readability.
second you are calling mostFrequest on the class Student, not an instance of it. Use the method on an instance instead:
student = Student(row)
student.MostFrequent()
use Student().MostFrequent()
edit:
beware that you use class attributes and this is dangerous. here an example:
>>> class Person:
... name = None
... hobbies = []
... def __init__(self, name):
... self.name = name
...
>>> a = Person('marco')
>>> b = Person('francesco')
>>> a.hobbies.append('football')
>>> b.hobbies
['football']
>>> a.name
'marco'
>>> b.name
'francesco'
>>> a.name = 'mario'
>>> b.name
'francesco'
>>> a.name
'mario'
>>>
as you can see i modify marco's hobbies and francesco's hobbies are modified consequentially.
What you probably want is to define most_frequent as a classmethod:
#classmethod
def most_frequent(cls):
for choice in cls.choice_list:
cls.choice_dict[choice] = cls.choice_dict.get(choice, 0) + 1
cls.mostFrequent = sorted([(v, k) for k, v in cls.choice_dict.items()], reverse=True)
return cls.mostFrequent
First, I recommend making function names lower case only.
The error you get results from the usage of MostFrequent as a static method. For this to work, you need to explicitly pass an instance of Student as first argument.
If called directly on an instance of Student, the instance will implicitly be passed as first argument.
Consider using the staticmethod decorator for static usage of functions.
You only rarely call methods on a class definition (Student)
Almost always, you create an instance of the class
someStudent = Student(someRow)
Then you call the method on the instance ("object"), someStudent.
someStudent.MostFrequent()
Student.MostFrequent means You're trying to use static method, not instance method. So You must first create instance by calling Student() and then call MostFrequent() on it.
P.S.: If this is not part of some arcane project, I urge you to follow PEP 8 and use most_frequent as method name.
in your class def, the method definition
def MostFrequent(self,mostFrequent):
has the extra variable mostFrequent that you probably don't want there. Try changing to :
def MostFrequent(self):

Categories