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()
Related
This is my experimenting code:
def settingValues():
hi = "Hello"
name = "Jake"
isTrue = True
def callingValues():
print(hi, name, isTrue)
settingValues()
callingValues()
Obviously this emmits an error...
Is there an easy way to transfer the variables throughout the two functions?
What I will be using this for requires setting quite a lot of variables... so I cant use 'global' for all of them. :)
Just use OOP:
class SomeClass:
def __init__(self):
self.hi = "Hello"
self.name = "Jake"
self.isTrue = True
def callingValues(self):
print(self.hi, self.name, self.isTrue)
sc = SomeClass()
sc.callingValues()
The easiest way would be to define them as globals, which could then be accessed from all the functions in the same module
hi = ""
name = ""
isTrue = False
def settingValues():
hi = "Hello"
name = "Jake"
isTrue = True
def callingValues():
print(hi, name, isTrue)
settingValues()
callingValues()
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))
I am just learning classes in Python and for the past day I am stuck with the below.
I am trying to use a user input (from the main() function) to change the value of an attribute in the class.
I have been throught the #property and #name.setter methods that allow you to change the value of a private attribute.
However I am trying to find out how you can use user input to change the value of an attribute that is not private.
I came up with the below but it does not seem to work. The value of the attribute remains the same after I run the program. Would you have any ideas why?
class Person(object):
def __init__(self, loud, choice = ""):
self.loud = loud
self.choice = choice
def userinput(self):
self.choice = input("Choose what you want: ")
return self.choice
def choiceimpl(self):
self.loud == self.choice
def main():
john = Person(loud = 100)
while True:
john.userinput()
john.choiceimpl()
print(john.choice)
print(john.loud)
main()
In choiceimpl you are using == where you should use =.
Like stated before, you are using a comparison with == instead of the =.
Also you are returning self.choice in userinput as a return value, but never use it, because you set self.choice equal to input.
Shorter example:
class Person:
def __init__(self, loud):
self.loud = loud
def set_loud(self):
self.loud = input("Choose what you want: ")
def main():
john = Person(100)
while True:
john.set_loud()
print(john.loud)
main()
1) Change: '=='(comparison operator) to '='(to assign)
2) Inside class:
def choiceimpl(self,userInp):
self.loud = self.userInp
3) Outside class
personA = Person(loud) # Create object
userInp = raw_input("Choose what you want: ") # Get user input
personA.choiceimpl(userInp) # Call object method
When using #classmethod this is passed first instead of self. Now inside the method with this decorator i need to call functions that are not defined inside this decorator but are defined in the class. How can i call the two functions get_int_input and get_non_int_input so that i can pass them to the return cls(name,pay_rate,hours) statement?
class Employee(object):
def __init__(self,name,pay_rate,hours):
self.name = name
self.pay_rate = pay_rate
self.hours = ("mon","tues","wed","thursday","friday","saturday","sunday")
def get_int_input(prompt):
while True:
pay_grade = raw_input(prompt)
try:
i = int(pay_grade)
except ValueError:
print "Int Only"
else:
return i
def get_non_int_input(prompt):
while True:
a_name = raw_input(prompt)
try:
i = int(a_name)
except ValueError:
return a_name
else:
print " Strings Only"
#classmethod
def from_input(cls):
day_count = 1
hours = ("m","tue","w","thur","f","s","sun")
while day_count <= 7:
for day in hours:
day = input(" Enter hours for day " + str(day_count) + "--- ")
day_count += 1
return cls(name,pay_rate,hours)
name = get_non_int_input("\n Enter new employee name\n")
pay_rate = get_int_input("Enter pay rate ")
employee = Employee.from_input()
print str(employee)
You would add the #staticmethod decorator before the other two classes. Since they don't take either the Employee class or one of its instances as their first argument, they operate independently of a particular class or instance, and in this sense are "static".
A method decorated in this manner is an attribute of its containing class, and is called as a class attribute, for example:
>>> class Foo(object):
... #staticmethod
... def bar():
... print 'called the static method'
...
>>> Foo.bar()
called the static method
This works the same way if you're calling Foo.bar() from inside one of Foo's class methods.
There are some other problems here, though - I would advise you to seek more comprehensive review and advice.
You defined get_int_input and get_non_int_input inside the Employee class, which means that (by default) they should take an instance of Employee as the first argument. Your code is breaking that rule, which is probably the cause of problems.
Use #staticmethod decorator to indicate that get_int_input and get_non_int_input should not take an instance of Employee as the first argument.
you seem to be missing some core concept of programming
you should probably look up namespaces and scope in google.
you should probably not talk down to john.r.sharp as he is very helpful and I would hazard a guess that if you continue programming you will have many many more problems that you come to SO for help with
all that said here is your fixed code
#first pull these two functions out of your class they have nothing to do with employee
#they should just be normal functions #
#... if you wanted to make them part of a class make an input class and add them as static methods to that
def get_int_input(prompt):
while True:
pay_grade = raw_input(prompt)
try:
i = int(pay_grade)
except ValueError:
print "Int Only"
else:
return i
def get_non_int_input(prompt):
while True:
a_name = raw_input(prompt)
try:
i = int(a_name)
except ValueError:
return a_name
else:
print " Strings Only"
class Employee(object):
def __init__(self,name,pay_rate,hours):
self.name = name
self.pay_rate = pay_rate
self.hours = ("mon","tues","wed","thursday","friday","saturday","sunday")
#classmethod
def from_input(cls):
day_count = 1
hours = ("m","tue","w","thur","f","s","sun")
while day_count <= 7:
for day in hours:
day = input(" Enter hours for day " + str(day_count) + "--- ")
day_count += 1
#name and pay_rate must be defined prior to using them in your return function ...
name = get_non_int_input("\n Enter new employee name\n")
pay_rate = get_int_input("Enter pay rate ")
#now that you have all the info just return it
return cls(name,pay_rate,hours)
employee = Employee.from_input()
print str(employee)
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):