How to access local variables within a class - python

I am working on an assignment and am trying to access a local variable within a function that is in a class. Does anyone know how I can print a local variable from a function in a class? We are not allowed to print anything within our functions in the classes so I am wondering how I can do this.
def driver():
q = my_queue.Queue_()
for line in df:
if 'received' in line:
q.enqueue(line)
print("Adding job " + q.new_item.job_ID + " to the queue with the timestamp: " + q.new_item.time_stamp + ".")
print("The prority of the job is: " + q.new_item.job_priority)
print("The job type is: " + q.new_item.job_type)
if 'respond' in line:
q.dequeue()
print("Completed job " + q.current.job_ID + " in " + str(int(q.time_elapsed)) + " seconds.")
if 'active' in line:
q.active_jobs()
print("Total number of jobs: " + str(len(q.active_jobs.temp)))
print("Average priority: " + str(q.active_jobs.average))
I am trying to print the last two lines but that is where the error is occurring.
The error I am getting is: AttributeError: 'function' object has no attribute 'temp'.
This is the function within the class:
def active_jobs(self):
if self.head == None:
pass
# print("No Jobs Available. ")
else:
current = self.head
self.temp = []
while current:
self.temp.append(current.get_data())
current = current.get_next()
return self.temp
# print("Total number of jobs: " + str(len(self.temp)))
self.priority = []
for i in range(len(self.temp)):
self.priority.append(self.temp[i][2])
x = [int(i) for i in self.priority]
self.average = sum(x) / len(x)
return self.average

active_jobs creates the temp instance attribute. Assuming the instance is q; access that attribute with q.temp.

Related

How to print class object data?

I can't get the data within each ticket object to print. What am I doing wrong? I've never used __dict__ beofre but do I need to? Output I am getting is
t1 = Ticket_1()
TypeError: __init__() missing 3 required positional arguments: 'Ticket_1', 'Ticket_2', and 'Ticket_3'
Code:
class Ticket: #creates ticket and makes a count of each ticket created
counter = 2000 # static field counter + 2000
counter += 1
ticket_number = counter
def __init__(self, Ticket_1, Ticket_2, Ticket_3):
self.Ticket_1 = Ticket_1()
self.Ticket_2 = Ticket_2()
self.Ticket_3 = Ticket_3()
class Ticket_1(Ticket):
def ticketVariables(self, creator_name, staff_id, email, issue):
creator_name = "martha"
staff_id = "MARTHAT"
email = "martha#whitecliffe.co.nz"
issue = "monitor is broken"
ticket_list = []
ticket_list.append(ticket_number)
ticket_list.append(creator_name)
ticket_list.append(staff_id)
ticket_list.append(email)
ticket_list.append(issue)
def display(self):
print("Ticket Number: " + ticket_list[0])
print("Ticket Creator: " + ticket_list[1])
print("Staff ID: " + ticket_list[2])
print("Email Address: " + ticket_list[3])
print("Description: " + ticket_list[4])
class Ticket_2(Ticket):
def ticketVariables(self, creator_name, staff_id, email, issue):
creator_name = "Not Specified"
staff_id = "PAULG"
email = "Not Specified"
issue = "need to change password"
ticket_list = []
ticket_list.append(ticket_number)
ticket_list.append(creator_name)
ticket_list.append(staff_id)
ticket_list.append(email)
ticket_list.append(issue)
def display(self):
print("Ticket Number: " + ticket_list[0])
print("Ticket Creator: " + ticket_list[1])
print("Staff ID: " + ticket_list[2])
print("Email Address: " + ticket_list[3])
print("Description: " + ticket_list[4])
class Ticket_3(Ticket):
def ticketVariables(self, creator_name, staff_id, email, issue):
creator_name = "Not Specified"
staff_id = "CARLH"
email = "carlhemmingway#whitecliffe.co.nz"
issue = "wifi isn't working"
ticket_list = []
ticket_list.append(ticket_number)
ticket_list.append(creator_name)
ticket_list.append(staff_id)
ticket_list.append(email)
ticket_list.append(issue)
def display(self):
print("Ticket Number: " + ticket_list[0])
print("Ticket Creator: " + ticket_list[1])
print("Staff ID: " + ticket_list[2])
print("Email Address: " + ticket_list[3])
print("Description: " + ticket_list[4])
class main:
t1 = Ticket_1()
t2 = Ticket_2()
t3 = Ticket_3()
myobj = Ticket(t1, t2, t3)
t1.display()
t2.display()
t3.display()
Clearly for now, I'm just trying to print the information within each ticket object, but also not sure if I should be using init to define those variables or not...?

Iterating through owned ec2.snapshots [duplicate]

This question already has an answer here:
How to use boto3 to get a list of EBS snapshots owned by me?
(1 answer)
Closed 2 years ago.
Im trying to print out every snapshot that hasn't got the specific Tag "CostReference" inside my aws account.
To Iterate through the snapshots I'm using:
for snapshot in snapshots:
if(not costreferencetag_isset_snapshot(snapshot)):
print("[SNAPSHOT] " + str(snapshot))
print("[INFO]: No CostReferenceTag!! \n")
missingtagginginfo = missingtagginginfo + str(snapshot) + ": No CostReferenceTag\n"
count_snapshot += 1
continue
else:
costreference_snapshot = get_costreference_snapshot(snapshot)
if costreference_snapshot not in managedpsp:
print("[SNAPSHOT] " + str(snapshot))
print("[INFO]: The PSP: " + costreference_snapshot + " of: " + str(snapshot) + " is WRONG! \n")
missingtagginginfo = missingtagginginfo + str(snapshot) + " " + costreference_snapshot + ": Wrong PSP\n"
count_snapshot += 1
print(count_snapshot)
So far so good the code is working, but I'm also getting the public Snapshots that are owned by amazon, wich have no relevance for me.
Is there any way to filter those public snapshots?
Greets
Code for the other functions:
def costreference_isset(instance):
#Searching for Instance without CostReference-tags
if instance.tags is None:
print("[INFO]: No Tags have been set yet:")
return(False)
#Searching for CostReference-tags
for t in instance.tags:
if t['Key'] == 'CostReference':
return(True)
return(False)
def get_costreferencetag(instance):
for t in instance.tags:
if t['Key'] == "CostReference":
return(str(t['Value']))
return(False)
managedpsp is a list with valid Costreference - tags
Solved it with:
for snapshot in snapshots.filter(OwnerIds= ['self']):
if(not costreferencetag_isset_snapshot(snapshot)):
print("[SNAPSHOT] " + str(snapshot))
print("[INFO]: No CostReferenceTag!! \n")
missingtagginginfo = missingtagginginfo + str(snapshot) + ": No CostReferenceTag\n"
count_snapshot += 1
continue
else:
costreference_snapshot = get_costreference_snapshot(snapshot)
if costreference_snapshot not in managedpsp:
print("[SNAPSHOT] " + str(snapshot))
print("[INFO]: The PSP: " + costreference_snapshot + " of: " + str(snapshot) + " is WRONG! \n")
missingtagginginfo = missingtagginginfo + str(snapshot) + " " + costreference_snapshot + ": Wrong PSP\n"
count_snapshot += 1
print(count_snapshot)
Try using the filter owner-id with your own account number.
Check here for the CLI reference: describe-snapshots — AWS CLI Command Reference

How can I write this to a file

class PersonalInfo:
def set_titles(self, title):
self.__titles = title
def set_names(self, name):
self.__names = name
def set_addresses(self, add):
self.__addresses = add
def set_ages(self, age):
self.__ages = age
def set_numbers(self, number):
self.__numbers = number
# Accessor methods
def get_titles(self):
return self.__titles
def get_names(self):
return self.__names
def get_addresses(self):
return self.__addresses
def get_ages(self):
return self.__ages
def get_numbers(self):
return self.__numbers
def main():
# references PersonalInfo object
info = PersonalInfo()
# stores values in the object
info.set_titles(input("Enter Mr, Mrs, Miss:"))
info.set_names(input("Enter full name:"))
info.set_addresses(input("Enter address:"))
info.set_ages(input("Enter age:"))
info.set_numbers(input("Enter number:"))
#displays values stored in object's fields
print("Name: " + info.get_titles() + " " + info.get_names() + "\n"
+"Address: " + info.get_addresses() + "\n"
+ "Birth: " + info.get_ages() + "\n"
+ "Number: " + info.get_numbers() + "\n")
main()
main()
I want this to be printed out 2 times since I have 2 users who will answer the questions, but I can't seem to understand how to save the input answers in a text file. Can someone please give me an example??:)
I'm such a noob at this
Change your main() to init(self): And call it twice if you need run it twice. You could write a method to output the data to a file instead of including it in init if you wanted to.
def __init__(self):
# stores values in the object
self.title = self.set_titles(input("Enter Mr, Mrs, Miss: "))
self.name = self.set_names(input("Enter full name: "))
self.age = self.set_ages(input("Enter age: "))
self.address = self.set_addresses(input("Enter address: "))
self.number = self.set_numbers(input("Enter number: "))
# displays values stored in object's fields
print("Name: " + self.get_titles() + " " + self.get_names() + "\n"
+"Address: " + self.get_addresses() + "\n"
+ "Birth: " + self.get_ages() + "\n"
+ "Number: " + self.get_numbers() + "\n")
# Appends data to file
outfile = open('data_from_user.txt','a')
outfile.write("Name: " + self.get_titles() + " " + self.get_names() + "\n")
outfile.write("Address: " + self.get_addresses() + "\n")
outfile.write("Birth: " + self.get_ages() + "\n")
outfile.write("Number: " + self.get_numbers() + "\n")
outfile.close()
person_1 = PersonalInfo()
person_2 = PersonalInfo()
# storing data inside string
string = 'NAME: {} \n Address: {} \n Birth: {} \n Number: {} \n'.format(info.get_titles(),info.get_names(),
info.get_addresses(),info.get_ages(),info.get_numbers())
# printing 2 times
print(string,string,sep='\n')
# writing in a file
x = open('filename','a')
x.write(string)
x.close()

Dynamically create a Python function with positional or key-word args, not from a string

Over at this question there are some neat tricks for generating functions on the fly in Python.
In my use case, however, I need to make sure the generated function has a particular name and particularly-named arguments as well. I'll give an example.
Suppose I want to parse a Yaml file that has a format like this:
Root:
my_idea:
type: conditional
conditionals:
- foo
- bar
query: >
SELECT * FROM some_table
This needs to be interpreted as: create a function for me called "my_idea" which has arguments named "foo" and "bar" (in that order).
When the function is called, use some existing tool to connect to a database and prepare the query element from the Yaml file. Then add a WHERE clause based on the conditional names matching the values passed in to the function for that argument.
So, after this happens, a user should be able to call:
my_idea(10, 20)
and it would be equivalent to executing the query
SELECT * FROM some_table WHERE foo = 10 AND bar = 20
If I used def to make the function, it might be something like this:
def my_idea(arg1, arg2):
query = (query_retrieved_from_file +
" WHERE {}={} AND {}={}".format(arg1_name_from_file,
arg1,
arg2_name_from_file,
arg2))
connection = ExistingLibraryConnectionMaker()
return connection.execute(query).fetchall()
This is a really simplified example -- I'm not endorsing the specifics of this little function, just trying to illustrate the idea.
The question is: how to create this on-the-fly, where the name of the function and the name of the positional arguments are extracted from a text file?
In the other question, there is some example code:
import types
def create_function(name, args):
def y(): pass
y_code = types.CodeType(args,
y.func_code.co_nlocals,
y.func_code.co_stacksize,
y.func_code.co_flags,
y.func_code.co_code,
y.func_code.co_consts,
y.func_code.co_names,
y.func_code.co_varnames,
y.func_code.co_filename,
name,
y.func_code.co_firstlineno,
y.func_code.co_lnotab)
return types.FunctionType(y_code, y.func_globals, name)
but it's not clear how to have the positional args reflect what I want them to semantically reflect.
The other solution I found was like this:
import types
import sys,imp
code = """def f(a,b,c):
print a+b+c, "really WoW"
"""
module = imp.new_module('myfunctions')
exec code in module.__dict__
module.f('W', 'o', 'W')
Output:
WoW really WoW
This is much closer, but requires all of the code to be embedded in a string format. I'm looking to build up a function programmatically, and across a reasonably large set of options, so handling them all deep in strings is not doable.
LL Parser example, made for fun.
Generates
Generated Code:
def my_idea(arg0,arg1,atasdasd):
query = "SELECT * FROM some_table WHERE foo==arg0 AND bar>arg1"
connection = ExistingLibraryConnectionMaker()
return connection.execute(query).fetchall()
def lool(hihi,ahah):
query = "SELECT * FROM some_table WHERE foo<=hihi AND bar<ahah"
connection = ExistingLibraryConnectionMaker()
return connection.execute(query).fetchall()
###end
from
Root:
my_idea:
args :
-arg0
-arg1
-atasdasd
type: conditional
conditional:
-foo == arg0
-bar > arg1
query:
SELECT * FROM some_table
lool:
args :
-hihi
-ahah
type: conditional
conditional:
- foo <= hihi
- bar < ahah
query:
SELECT * FROM some_table
Can handle any number of functions.
Code:
from __future__ import print_function
import re
import traceback
import sys
glIndex = 0
code = ""
class Token(object):
def __init__(self, pattern, name, value=None, transform=None):
self.pattern = pattern
self.name = name
self.value = value
tokens = {
Token(r"(\()","lpar"),
Token(r"(\))","rpar"),
Token(r"(\d(?:\.\d*)?)","number"),
Token(r"(\+)", "plus"),
Token(r"(?!\-\-)(\-)","minus"),
Token(r"(?!\=\=)(\=)","egal"),
Token(r"(;)","colon"),
Token(r"([a-zA-Z][a-zA-Z0-9_]*)(?=[\s\:])","unique"),
Token(r"(\=)\=","=="),
Token(r"(\>\=)",">="),
Token(r"(\<\=)","<="),
Token(r"(?!\>\=)(\>)",">"),
Token(r"(?!\<\=)(\<)","<"),
Token(r"\:",":"),
Token(r"\*","*")}
def peekComp(l):
symbol = None
if peekMatch(l,">=") :
symbol = ">="
elif peekMatch(l,"<=") :
symbol = "<="
elif peekMatch(l,">") :
symbol = ">"
elif peekMatch(l,"<") :
symbol = "<"
elif peekMatch(l,"==") :
symbol = "=="
return symbol
def parseListItem(l):
match(l,"minus")
u = match(l,"unique")
return u
def parseTitle(l):
val = match(l,"unique")
match(l,":")
return val
def parseComp(l):
match(l,"minus")
lvar = match(l,"unique")
symbol = peekComp(l)
if symbol == None:
print("Homemaid SyntaxError: needed a comp symbol")
exit(1)
symbolS = match(l,symbol)
rvar = match(l,"unique")
return (lvar,symbolS,rvar)
def tokenize(s):
l=[]
i=0
while i < s.__len__():
if re.match(r"\s",s[i]):
i+=1
continue
foundAMatch = False
for t in tokens:
pat = "^(" + t.pattern + ").*"
#print("trying with pat :'"+pat+"';")
res = re.match(pat,s[i:])
if res != None:
print("Match: -what : '" + res.group(1) + "' -to-token-named :'" + t.name + "'; \t\tTotal text : '" + res.group(0) + "';" )
i += res.group(1).__len__()
foundAMatch = True
l.append(Token(t.pattern,t.name,res.group(1)))
break
if not foundAMatch:
print("Homemaid SyntaxError: No match for '" + s[i:] + "';")
quit()
return l
def syntaxError(l,fname):
global glIndex
print("Homemaid SyntaxError: '"+l[glIndex].name+"'")
print(fname)
quit()
def match(tokens, wanted):
global glIndex
if tokens[glIndex].name == wanted:
glIndex+=1
print("Matched '" + tokens[glIndex-1].value + "' as '" + wanted + "';")
return tokens[glIndex-1].value
else:
print("Homemaid Syntax Error : Match failed on token '" + tokens[glIndex].name + "' with wanted token '" + wanted + "' and text '" + tokens[glIndex].value + "';")
exit(1)
def peekMatch(token, wanted):
global glIndex
if glIndex < token.__len__() and token[glIndex].name == wanted:
print("Matched "+wanted)
return True
else:
return False
def parse(l):
#root
localCode = ""
rootName = parseTitle(l)
print("Root : " + rootName)
#parse funcitons
while peekMatch(l,"unique"):
localCode += parseFunction(l)
print("Done with the parsing.")
return localCode
def parseFunction(l):
print("CAME IN PARSE FUNCITON")
#function name
localCode = "\n\ndef " + parseTitle(l) +"(";
#args
args = set()
title = parseTitle(l)
if title!="args":
print("Homemaid Syntax Error : title should be 'args', was instead '" + title + "';")
exit(1)
while(peekMatch(l,"minus")):
lastArg = parseListItem(l)
args.add(lastArg)
localCode += lastArg
if peekMatch(l,"minus") :
localCode += ","
localCode += "):\n"
#type
if parseTitle(l)!="type":
print("Homemaid Syntax Error : title should be 'type'")
exit(1)
#query
##query name
queryTypeName = match(l, "unique")
##query args
queryTypeArgs = []
if parseTitle(l)!=queryTypeName:
print("Homemaid Syntax Error : title should be the same as the name of the query.")
exit(1)
while(peekMatch(l,"minus")):
queryTypeArgs.append(parseComp(l))
##query sql code
if parseTitle(l) != "query":
print("Homemaid Syntax Error : title should be 'query'.")
exit(1)
initialQuery = parseBasicSqlQuery(l)
if queryTypeName == "conditional" and queryTypeArgs.__len__() <= 0 :
print("Homemaid Syntax error : Conditional query needs at least one arg.")
exit(1)
##query codegen
localCode += "\tquery = \"" + initialQuery + " WHERE "
first = True
if queryTypeName == "conditional":
for lArg, cmpSign, rArg in queryTypeArgs:
if not first:
localCode += " AND "
if rArg in args:
first = False
localCode += lArg + cmpSign + rArg
else:
print("queryTypeArgs : " + str(queryTypeArgs))
print("Homemaid Logic Error: Query arg '" + rArg + "' is not in the funciton args " + str(args) + ".")
quit(1)
localCode += "\"\n\tconnection = ExistingLibraryConnectionMaker()\n\treturn connection.execute(query).fetchall()"
return localCode
def parseBasicSqlQuery(l):
selectS = match(l,"unique")
whatS = match(l,"*")
fromS = match(l,"unique")
tableNameS = match(l,"unique")
if selectS.upper() != "SELECT" or fromS.upper() != "FROM":
print("Homemaid Syntax error: bad basic sql.")
exit(0)
return selectS + " " + whatS + " " + fromS + " " + tableNameS
def parseVal(l):
if match(l, "lpar"):
parseVal(l)
match(l, "rpar")
elif peekMatch(l, "number") and (peekMatch(l, "plus") or peekMatch(l, "minus") or peekMatch(l, "equal")):
glIndex+=1
print("peekMatched!")
parseOp(l)
parseVal(l)
elif match(l, "number"):
pass
else:
syntaxError(l, "parseVal")
print("** Parsed val.")
def parseOp(l):
if match(l, "plus"):
pass
elif match(l, "minus"):
pass
elif match(l, "egal"):
pass
else:
syntaxError(l, "parseVal")
print("** Parsed op.")
if __name__ == "__main__":
with open("sqlGenTest.SQLGEN", "rw") as file:
print("File:\n'")
text = file.read()
print(text + "'\n")
tokens = tokenize(text)
names = map(lambda x: str("'" + x.name + "'" + " : " + "'" + x.value + "'"), tokens)
map(print,names)
code = parse(tokens)
print("")
print("###Generated Code:\n" + code)
print("###end")
print()

NameError: name 'countrychoice' is not defined

I'm having some trouble with the current program I'm writing.
I'm letting the user type in a country, and then a city city in that country, and then see a weather forecast for the choosen city using API.
I'm using a class, like this:
class requestChoice:
def __init__(self):
self.countrychoice = None
self.citychoice = None
def countryChoice(self):
self.countrychoice = input("Enter which country your city is in(in english): ")
def cityChoice(self):
self.citychoice = input("Enter the name of the city: ")
And my main program looks like this:
from requestchoice import requestChoice
import requests
if __name__ == '__main__':
"""Introducion"""
print ("\nThis program lets you see a weather forecast for your choosen city.")
rc = requestChoice()
while True:
print("\nWhen you have typed in country and city, press 3 in the menu to see the weather forecast for your choice.\n")
menu = input("\nPress 1 for contry\nPress 2 for city\nPress 3 to see forecast\nPress 4 to exit\n")
if menu == "1":
rc.countryChoice()
elif menu == "2":
rc.cityChoice()
elif menu == "3":
r = requests.get("http://api.wunderground.com/api/0def10027afaebb7/forecast/q/" + countrychoice + "/" + citychoice + ".json")
data = r.json()
try:
for day in data['forecast']['simpleforecast']['forecastday']:
print (day['date']['weekday'] + ":")
print ("Conditions: ", day['conditions'])
print ("High: ", day['high']['celsius'] + "C", '\n' "Low: ", day['low']['celsius'] + "C", '\n')
except Exception as e:
print ("\nHave you typed in the correct country and city?\nBecause we got a" ,e, "error")
else:
print ("\nGoodbye")
break
When I run my program I get the error NameError: name 'countrychoice' is not defined. It is going to be the same error with the citychoice. I've tried creating a list in my class and append the countrychoice to the list but without any luck. How am I supposed to make it work as wished?
You are getting a NameError on here:
r = requests.get("http://api.wunderground.com/api/0def10027afaebb7/forecast/q/" + countrychoice + "/" + citychoice + ".json")
because you have no names countrychoice and citychoice defined. Perhaps you meant to use rc.countrychoice and rc.citychoice instead?
You have to access them with the corresponding object name. In this case
rc.countrychoice
rc.citychoice
So, this line
r = requests.get("http://api.wunderground.com/api/0def10027afaebb7/forecast/q/" + countrychoice + "/" + citychoice + ".json")
becomes
r = requests.get("http://api.wunderground.com/api/0def10027afaebb7/forecast/q/" + rc.countrychoice + "/" + rc.citychoice + ".json")
You need to use rc.countrychoice and rc.citychoice here
r = requests.get("http://api.wunderground.com/api/0def10027afaebb7/forecast/q/" + rc.countrychoice + "/" + rc.citychoice + ".json")

Categories