Getting Bound method error when calling function from another class - python

So i have a class called read that is full of Def, im trying to call one of them and i get a 'Bound method' error, what do you think.
from ExcelRead import Read
t = Read()
L = t.other
print L
def Other():
User = []
Excel = []
lst = OpenExcel()
User = OpenFile("whatever.txt")
for item in lst:
Excel.append(str(item.value))
Excel = [line.strip() for line in Excel]
Differ = comp(User, Excel)
print Differ
This is calling other functions
Where other is the name of the function i want to call, this function does return a value. thanks for your help

You aren't getting any error at all here. You're simply printing the function, which is indeed bound.
As with any other function in Python, if you want to call it, you need to use parentheses:
L = t.other()
print L

Related

How to use a string as an already exist list function in python?

I want to use a string as an already exists list function.
For example i got from a user as input: 'append'
How can i use this string as a function directly?
For example:
function_name = str(input(n)) # let say it is append
arr = []
arr.function_name(9) #Of course it is not working because it is string. Not a function.
Use getattr.
>>> a = []
>>> getattr(a, 'append')(1)
>>> a
[1]
That being said, it's not the best idea to execute arbitrary code based on user input. You should check the input against a collection of allowed methods first.
All functions are attributes of the respective object. You can use the getattr function to get the function callable and then call it.
For Eg. ,
function_name = str(input("")) # let say it is append
arr = []
#Get the attribute and call it
# You can check if callable(function_to_call) to make sure its a function as well.
function_to_call = getattr(arr, function_name)
function_to_call(10)
print(arr)
The method you are using is not possible.
But you can use this method instead...
function_name = str(input(n))
arr = []
if function_name == "append":
arr.append(9)
or you can use getattr:
function_name = str(input(n))
arr = []
getattr(arr, fucntion_name)(9)

I am getting an error which says lowercase_lines is not defined

import string
def getData(filename):
with open(filename,'r') as f:
lines=[line.rstrip() for line in f]
lines=[x.lower() for x in lines]
return lines
filename="bibleSentences.txt"
getData(filename)
def normalize(filename):
lowercase_lines=[x.lower() for x in getData(filename)]
return lowercase_lines
normalize(filename)
def replace_all(text,dic):
for p in normalize(filename):
for i,j in dic.iteritems():
text=text.replace(i,j)
print (text)
return text
text=lowercase_lines
dic={"and":"","the" :"", "in":"", "it":"", "was":"", "his":"", "of":"", "so":"" }
print(replace_all(normalize))
The issue is that lowercase_lines is a local variable to the normalize function, which you are calling without saving its return to a variable.
Just put lowercase_lines = normalize(filename)
The only place lowercase_lines is defined is in this function:
def normalize(filename):
lowercase_lines=[x.lower() for x in getData(filename)]
return lowercase_lines
But that variable is in what's called "function scope", which means it only exists until that function exists. You need to capture the value being returned from the function so that you can use it outside the function. But you are actually doing that in the line:
for p in normalize(filename):
I don't see what value the line:
text=lowercase_lines
has for you. You are already using the result of the normalize() function above that. I think removing that line is what you want to do, unless there is other code further down that uses the value text.
Your functions are all returning values but you need to set them to a variable:
lines = getData(filename)
lowercase_lines = normalize(filename)
etc.

Call many python functions from a module by looping through a list of function names and making them variables

I have three similar functions in tld_list.py. I am working out of mainBase.py file.
I am trying to create a variable string which will call the appropriate function by looping through the list of all functions. My code reads from a list of function names, iterates through the list and running the function on each iteration. Each function returns 10 pieces of information from separate websites
I have tried 2 variations annotated as Option A and Option B below
# This is mainBase.py
import tld_list # I use this in conjunction with Option A
from tld_list import * # I use this with Option B
functionList = ["functionA", "functionB", "functionC"]
tldIterator = 0
while tldIterator < len(functionList):
# This will determine which function is called first
# In the first case, the function is functionA
currentFunction = str(functionList[tldIterator])
Option A
currentFunction = "tld_list." + currentFunction
websiteName = currentFunction(x, y)
print(websiteName[1]
print(websiteName[2]
...
print(websiteName[10]
Option B
websiteName = currentFunction(x, y)
print(websiteName[1]
print(websiteName[2]
...
print(websiteName[10]
Even though it is not seen, I continue to loop through the iteration by ending each loop with tldIterator += 1
Both options fail for the same reason stating TypeError: 'str' object is not callable
I am wondering what I am doing wrong, or if it is even possible to call a function in a loop with a variable
You have the function names but what you really want are the function objects bound to those names in tld_list. Since function names are attributes of the module, getattr does the job. Also, it seems like list iteration rather than keeping track of your own tldIterator index would suffice.
import tld_list
function_names = ["functionA", "functionB", "functionC"]
functions = [getattr(tld_list, name) for name in function_names]
for fctn in functions:
website_name = fctn(x,y)
You can create a dictionary to provide a name to function conversion:
def funcA(...): pass
def funcB(...): pass
def funcC(...): pass
func_find = {"Huey": funcA, "Dewey": funcB, "Louie": FuncC}
Then you can call them, e.g.
result = func_find["Huey"](...)
You should avoid this type of code. Try using if's, or references instead. But you can try:
websiteName = exec('{}(x, y)'.format(currentFunction))

FastQ programming error

So I'm trying to parse a FastQ sequence, but I'm a beginner to Python, and I'm a little confused as to why my code isn't working. This is what the program is supposed to carry out:
if I enter the FASTQ seqname line...
#EAS139:136:FC706VJ:2:2104:15343:197393
...then the program should output:
Instrument = EAS139
Run ID = 136
Flow Cell ID = FC706VJ
Flow Cell Lane = 2
Tile Number = 2104
X-coord = 15343
Y-coord = 197393
Here's my unfinished code thus far:
class fastq:
def __init__(self,str):
self.str = inStr.replace ('#',' ').split (':')
def lists (self,parameters):
self.parameters = ("Instrument","Run ID","Flow Cell ID","Flow Cell Lane","Tile Number","X-coordinates","y-coordinates")
def zip (self,myZip,zippedTuple):
self.Zip = zip(self.parameters,self.transform)
self.zippedTuple = tuple(myZip)
print (tuple(myZip))
def main():
seq = input('Enter FastQ sequence:')
new_fastq = fastq(str)
new_fastq.lists()
new_fastq.zip()
main()
The reason that your code isn't working is that it's more-or-less entirely wrong. To address your errors in the order we reach them when trying to run the program:
main:
new_fastq = fastq(str) does not pass the seq we just input, it passes the built-in string type;
__init__:
Calling the argument to fastq.__init__ str is a bad idea as it masks the very built-in we just tried to pass to it;
But whatever you call it, be consistent between the function definition and what is inside it - where do you think inStr is coming from?
lists:
Why is this separate to and not even called by __init__?
Why don't you pass any arguments?
What is the argument parameters even for?
zip:
Rather than define a method to print the object, it is more Pythonic to define fastq.__str__ that returns a string representation. Then you can print(str(new_fastq)). That being said;
Again, you mask a built-in. On this occasion, it's more of a problem because you actually try to use the built-in inside the method that masks it. Call it something else;
Again, you put unnecessary arguments in the definition, then don't bother to pass them anyway;
What is self.transform supposed to be? It is never mentioned anywhere else. Do you mean self.str (which, again, should be called something else, for reasons of masking a built-in and not actually being a string)?
myZip is one of the arguments you never passed, and I think you actually want self.Zip; but
Why would you create x = tuple(y) then on the next line print(tuple(y))? print(x)!
Addressing those points, plus some bonus PEP-008 tidying:
class FastQ:
def __init__(self, seq):
self.elements = seq.replace ('#',' ').split (':')
self.parameters = ("Instrument", "Run ID", "Flow Cell ID",
"Flow Cell Lane", "Tile Number",
"X-coordinates", "y-coordinates")
def __str__(self):
"""A rough idea to get you started."""
return "\n".join(map(str, zip(self.parameters, self.elements)))
def main():
seq = input('Enter FastQ sequence: ')
new_fastq = FastQ(seq)
print(str(new_fastq))
main()

Global Variable Error in Python List

I am working on a function that would take an user's input for four people's names and to append them to a list. However with the code below I get this user error. However, when I declare significant_other as a global variable, I get an invalid syntax error. How would I fix my code?
Traceback (most recent call last):
File "mash.py", line 16, in <module>
print spouse()
File "mash.py", line 13, in spouse
significant_other = signficant_other.append(new_spouse)
NameError: global name 'signficant_other' is not defined
Here is the code.
import random
# import random module
def spouse():
# defined function
significant_other =[]
#empty list
for x in range(4):
# for loop for an iteration of four
new_spouse = str(raw_input("Type a person you would like to spend your life with."))
# new spouse input
significant_other = signficant_other.append(new_spouse)
#significant other gets added to the list
print spouse()
Thanks for your help with this.
You spelt significant_other like this signficant_other
plus you just need to do:
significant_other.append(new_spouse)
change your line:
significant_other = signficant_other.append(new_spouse)
To this:
significant_other.append(new_spouse)
Basically you cannot assign a append method because it by default returns None:
>>> a = []
>>> b = a.append(5)
>>> print b
None
And so if you change your code to signficant_other.append(new_spouse) It still fails because you made a small typo you've spelled significant as signficant
There are a few issues, firstly:
significant_other = signficant_other.append(new_spouse)
.append() will not return a list, it modifies the list and returns None.
Secondly, you're attempting to use print, but the function that you're calling doesn't return what you want, it returns None.
Additionally, there was a spelling issue, but the above two are more important.
Try this:
def spouse():
significant_other = []
for x in range(4):
new_spouse = str(raw_input("...."))
significant_other.append(new_spouse)
return significant_other
print spouse()

Categories

Resources