How can i access a variable from one function to another? - python

def move(self):
z = self.comboBox.currentText()
print(z)
Hospital = newtest.my_function()
i = Hospital.index(z)
print('The index of :', i)
user = newuser.my_function()
global (user[i])
print (user[i])
return user[i]
def my_doc():
url = 'https://test.com/steth/get-list'
myobj = {'mongoId': 'user[i]'}
x = requests.post(url, data = myobj)
y=x.json();
print(y)
my_doc()
I need to get user[i] in the second function my_doc.so i made user[i] global.But it is showing syntax error as
global (user[i])
^
SyntaxError: invalid syn

Just get the return of one function, and input it into the other.
class Obj:
def func1(self):
return "something"
# Assuming func2 is inside class.
def func2_class(self, something):
print(something)
# Assuming func2 is outside class.
def func2(something):
print(something)
obj = Obj()
something = obj.func1()
func2(something) # Outside class.
obj.func2(something) # Inside class.

Related

How to define decorator within the class?

I wanted to use decorator inside a class but I am getting positional error.
1.I dont want to use functools and import wraps.
2.Can we declare it within the class rather than defining decorator outside class?
Is there any other method to declare a decorator within a class?
from pytube import YouTube
if __name__ == "__main__":
class term :
# def __init__(self,u,v):
# self.url = u
# self.path = v
def check(func):
def parameters(self,u,v):
print(f"title:{YouTube(u).title}, views:{YouTube(u).views}, Length:{YouTube(u).length}")
func(u,v)
print("Yes done")
return parameters
# return check
#check
def video1(self,u,v):
# y = YouTube(u)
# print("Y is",y)
video1 = YouTube(u).streams.first().download(v)
print("Success")
return video1
u = input("Enter the video URL: ")
v = input("Enter the path: ")
t1 = term()
t1.video1(u,v)
print(t1)
If I initialise u,v inside class and call it via t1 and use it in methods like check it gives an error saying term has positional argument error.
If I initialise u,v inside instance t1 and call it via t1.video1 and use it in methods like check it gives an error saying video has no positional argument "v".
How to use decorators?Can you pls help me.
Here is just an example for you, (Modify as per your need) -
class term:
def check(func):
def parameters(self, u, v):
print(f"title:")
print("Yes done")
return func(self, u, v)
return parameters
#check
def video1(self, u, v):
print("Success")
return 'Hello'
Also, You are printing an object like
t1 = term()
t1.video1(u,v)
print(t1)
But, you should be printing like -
t1 = term()
result = t1.video1(u,v)
print(result)

Getting "TypeError: with staticmethid not callable"

I am getting an error about TypeError: 'staticmethod' object is not callable. Basically, you the input is a map of and given that you provide a pair of floats (pt,eta), the code should return the Y value of the bin that the particular values fall in.
I ve tried related thread (as possible duplicates) but does not seem to be getting the answer I am looking for.
Of course, if one has any recommendations how to even improve the code, that would be welcomed of course.
import ROOT as root
import sys,math
class SFs():
global etaBinsH
global get_EfficiencyData
global get_EfficiencyMC
global eff_dataH
global eff_mcH
global get_ScaleFactor
#staticmethod
def ScaleFactor(inputRootFile) :
#inputRootFile="Muon_IsoMu27.root"
eff_dataH = root.std.map("string", root.TGraphAsymmErrors)()
eff_mcH = root.std.map("string", root.TGraphAsymmErrors)()
#std::map<std::string, root.TGraphAsymmErrors *> eff_data
#std::map<std::string, root.TGraphAsymmErrors *> eff_mc
EtaBins=["Lt0p9", "0p9to1p2","1p2to2p1","Gt2p1"]
print inputRootFile
fileIn = root.TFile(inputRootFile,"read")
fileIn.ls()
HistoBaseName = "ZMassEta"
etaBinsH = fileIn.Get("etaBinsH")
#etaLabel, GraphName
nEtaBins = int(etaBinsH.GetNbinsX())
eff_data= []
eff_mc= []
#eff_mcH =root.TGraphAsymmErrors()
print "EtaBins...........",nEtaBins, len(EtaBins)
for iBin in range (0, nEtaBins) :
etaLabel = EtaBins[iBin]
GraphName = HistoBaseName+etaLabel+"_Data"
print GraphName,etaLabel
eff_data.append(fileIn.Get(str(GraphName)))
eff_dataH[etaLabel]=fileIn.Get(str(GraphName))
GraphName = HistoBaseName+etaLabel+"_MC"
eff_mc.append(fileIn.Get(str(GraphName)))
eff_mcH[etaLabel]=fileIn.Get(str(GraphName))
print eff_mcH[etaLabel].GetXaxis().GetNbins()
print eff_mcH[etaLabel].GetX()[5]
sff = get_ScaleFactor(46.8,2.0)
print "SFFFFFFFFFFFFFf",sff
#staticmethod
def get_ScaleFactor(pt, eta) :
efficiency_data = get_EfficiencyData(pt, eta)
efficiency_mc = get_EfficiencyMC(pt, eta)
if efficiency_mc != 0. :
SF = float(efficiency_data)/float(efficiency_mc)
else :
SF=1.
print "ScaleFactor::get_ScaleFactor(double pt, double eta) Scale Factor set to",SF,efficiency_data,efficiency_mc
return SF
#staticmethod
def get_EfficiencyMC(pt, eta) :
label = FindEtaLabel(eta,"mc")
#label= "Lt0p9"
binNumber = etaBinsH.GetXaxis().FindFixBin(eta)
label = etaBinsH.GetXaxis().GetBinLabel(binNumber)
ptbin = FindPtBin(eff_mcH, label, pt)
Eta = math.fabs(eta)
print "eff_mcH ==================",eff_mcH,binNumber,label,ptbin
#ptbin=10
if ptbin == -99 : eff =1
else : eff= eff_mcH[label].GetY()[ptbin-1]
if eff > 1. : eff = -1
if eff < 0 : eff = 0.
print "inside eff_mc",eff
return eff
#staticmethod
def get_EfficiencyData(pt, eta) :
label = FindEtaLabel(eta,"data")
#label= "Lt0p9"
binNumber = etaBinsH.GetXaxis().FindFixBin(eta)
label = etaBinsH.GetXaxis().GetBinLabel(binNumber)
print eff_dataH
ptbin = FindPtBin(eff_dataH, label, pt)
Eta = math.fabs(eta)
fileOut=root.TFile("out.root","recreate")
fileOut.cd()
eff_dataH[label].Write(label)
#ptbin=10
if ptbin == -99 : eff =1
else : eff= eff_dataH[label].GetY()[ptbin-1]
print "inside eff_data",eff
if eff > 1. : eff = -1
if eff < 0 : eff = 0.
print "inside eff_data",eff,pt,eta,label
return eff
#staticmethod
def FindPtBin( eff_map, EtaLabel, Pt) :
Npoints = eff_map[EtaLabel].GetN()
print Npoints, "for ===============>",eff_map[EtaLabel],eff_map[EtaLabel].GetN(),EtaLabel
#ptMAX=100
#ptMIN=90
ptMAX = (eff_map[EtaLabel].GetX()[Npoints-1])+(eff_map[EtaLabel].GetErrorXhigh(Npoints-1))
ptMIN = (eff_map[EtaLabel].GetX()[0])-(eff_map[EtaLabel].GetErrorXlow(0))
if Pt >= ptMAX : return Npoints
elif Pt < ptMIN :
return -99
else : return eff_map[EtaLabel].GetXaxis().FindFixBin(Pt)
#staticmethod
def FindEtaLabel(Eta, Which) :
Eta = math.fabs(Eta)
binNumber = etaBinsH.GetXaxis().FindFixBin(Eta)
EtaLabel = etaBinsH.GetXaxis().GetBinLabel(binNumber)
it=-1
if str(Which) == "data" :
it = eff_dataH.find(EtaLabel)
if str(Which) == "mc" :
it = eff_mcH.find(EtaLabel)
return EtaLabel
sf = SFs()
sff = sf.ScaleFactor("Muon_IsoMu27.root")
To piggyback a bit on #Felipe's answer, by not making all of your methods static, you can eliminate the need for the global declarations to share variables around, since that's what you are doing anyways:
class SFs():
def __init__(self):
# initialize your global vars instead as
# instance variables
self.etaBinsH = None
self.get_EfficiencyData = None
self.get_EfficiencyMC = None
self.eff_dataH = None
self.get_ScaleFactor = None
# don't make this static, then you have access to the self attributes and it makes
# your code a bit more explicit
def scale_factor(self, input_file):
self.eff_dataH = root.std.map("string", root.TGraphAsymmErrors)()
self.eff_mcH = root.std.map("string", root.TGraphAsymmErrors)()
EtaBins = ["Lt0p9", "0p9to1p2","1p2to2p1","Gt2p1"]
print(input_file) # print with parentheses makes this more portable between versions
fileIn = root.TFile(input_file, "read")
# Now you can use this through self, which is more pythonic
self.etaBinsH = fileIn.Get("etaBinsH")
nEtaBins = int(self.etaBinsH.GetNbinsX())
eff_data, eff_mc = [], []
# rest of code
Your variables can then be shared via self, and the functions can also be accessed via self, otherwise staticmethod keeps access of self out of the function, which is why you can't call any of the other functions.
Classes are namespaces, and self allows you to tie variables to the instance-level namespace. By using global, you are trying to push those variables back to the global namespace to share them around, when really, you already have access to a namespace to share those variables in!
As a simple example:
class A:
# here is the namespace for the *class* A
x = 0 # x is an attribute on the class A, it is accessible on the class and instance level
def __init__(self):
self.y = 4 # y is now explicitly tied to an instance of A, and can be shared between *instance* methods of A
def use_y(self):
# because this is non-static, I have access to instance level
# variables, this is how you share them!
print(self.y)
# I also have access to class-level attributes
print(self.x)
#staticmethod
def use_x():
# I don't have access to self.y, because staticmethod takes that away
try:
print(self.y)
except NameError:
print("Couldn't make this work")
print(A.x) # have to print this as a *class-level* attribute, because self isn't defined here
a = A()
a.use_y()
# 4
# 0
a.use_x()
# Couldn't make this work
# 0
Some examples that might be helpful to see what is going on.
Example 1
class RandomClass():
global global_function
#staticmethod
def random_function(input):
print(global_function("test"))
return "random_function({})".format(input)
#staticmethod
def global_function(input):
return "global_function({})".format(input)
rc = RandomClass()
print(rc.random_function("Input!"))
Outputs
Traceback (most recent call last):
File "test.py", line 14, in <module>
print(rc.random_function("Input!"))
File "test.py", line 6, in random_function
print(global_function("test"))
TypeError: 'staticmethod' object is not callable
Example 2
class RandomClass():
#staticmethod
def random_function(input):
print(global_function("test"))
return "random_function({})".format(input)
#staticmethod
def global_function(input):
return "global_function({})".format(input)
rc = RandomClass()
print(rc.random_function("Input!"))
Output
Traceback (most recent call last):
File "test.py", line 12, in <module>
print(rc.random_function("Input!"))
File "test.py", line 4, in random_function
print(global_function("test"))
NameError: global name 'global_function' is not defined
Example 3
class RandomClass():
#staticmethod
def random_function(input):
print(RandomClass.global_function("test")) # Notice change here.
return "random_function({})".format(input)
#staticmethod
def global_function(input):
return "global_function({})".format(input)
rc = RandomClass()
print(rc.random_function("Input!"))
Output
global_function(test)
random_function(Input!)
Explanation
In short, a #staticmethod cannot access functions within its this class (whether defined with this or global), and instead must initialize a new and independent class to call a function within the class it resides in (example 3). As #C.Nivs mentioned, you should perhaps look into simply not using a class.

NameError: name 'convert_symbol_to_int' is not defined

I've got an error: NameError: name 'convert_symbol_to_int' is not defined when I run this code:
class ReadData():
def __init__(self, sheet_path):
self.book = xlrd.open_workbook(sheet_path)
self.sheet = self.book.sheet_by_index(1)
self.users = []
def read(self):
for row_index in range(2, self.sheet.nrows):
rows = self.sheet.row_values(row_index)
if rows[1] != '' and rows[2] != '' and rows[4] != '':
woman = convert_symbol_to_int(row[8])
man = convert_symbol_to_int(row[9])
def convert_symbol_to_int(self,arg):
if arg == '○':
return 2
elif arg == '×':
return 1
elif arg == '△':
return 0
else:
return -1
x = ReadData('./data/excel1.xlsx')
x.read()
I really cannot understand why this error happens.
Why can't I access convert_symbol_to_int? How should I fix this?
you should use
man = self.convert_symbol_to_int(row[9])
Exactly as Kalyan Reddy already answered, you have to call the method with self, which is a pointer to the class itself. The following example shows the difference between externally declared functions and methods defined within the class:
def hello():
print("hello, world!")
class Greeting(object):
def __init__(self, world):
self.world = world
def hello(self):
print("hello, {}!".format(self.world))
def make_greeting(self):
hello() # this will call the function we created outside the class
self.hello() # this will call the method defined in the class
The purpose of self has already been explained in this question:
What is the purpose of self?

Using return value inside another function

I have these two functions:
def check_channel_number(self):
print "***************Channel Checker *********************"
print ''
user_channel_number = int(re.sub('\D', '', raw_input("Enter a channel number, (3digit): "))[:3]);
channel = ("channelNr= '%d'") % (user_channel_number)
print channel
# channel_search = channel + str(user_channel_number)
datafile = file('output.txt')
found = False
for line in datafile:
if channel in line:
found = True
print 'The channel number you entered is correct and will be deleted'
return user_channel_number
print 'The channel number you entered is not on the planner'
return False
and
def delete_events(self):
if user_channel_number == True:
return 'The program number is correct and will be deleted'
# action = 'DeleteEvent'
menu_action = 'all'
book = 'RECYC:687869882'
arg_list = [('C:\\Users\\yke01\\Documents\\StormTest\\Scripts\\Completed'
'\\Utils\\UPNP_Client_Cmd_Line.py')]
arg_list.append(' --action=')
arg_list.append(action)
arg_list.append(' --ip=')
arg_list.append('10.10.8.89')
arg_list.append(' --objectId=')
arg_list.append(book)
subprocess.call(["python", arg_list])
print 'The program deleted successfully'
When I run my script, it says that user_channel_number is not defined globally. How can I use user_channel_number inside the delete_events function?
When you define a variable inside of a function, it is a local variable, meaning that it can only be accessed within that function.
Within a Class
It looks like you're inside a class, so you can make the variable accessible to all methods in the class by defining it like this:
def check_channel_number(self):
self.user_channel_number = ...
And then in your second function, you can use it like the following:
def delete_events(self):
if self.user_channel_number:
Outside of a class
If you aren't using methods inside of a class, you can instead use the global builtin.
For example,
def check_channel_number():
global user_channel_number
user_channel_number = ...
def delete_events():
if user_channel_number:
...
Using a value returned from a function
Instead in your first function, check_channel_number(), you can have it return user_channel_number. You can then call that function inside of delete_events(), like the following:
def check_channel_number():
user_channel_number = ...
return user_channel_number
def delete_events():
if check_channel_number():
...
Functions can not share their local variables. You can return the value from the first and pass it to the second:
def check_channel_number(self):
...
return user_channel_number
def delete_events(self):
user_channel_number = self.check_channel_number()
...
Or save value on the object:
def check_channel_number(self):
...
self.user_channel_number = user_channel_number
...
def delete_events(self):
if self.user_channel_number:
....
So I think when you call the check_channel_number function, user_channel_number is defined in there, so when you call delete_events, it has gone out of scope, maybe something like this would help?
user_channel_number = check_channel_number()
delete_events()
I'd probably have the user_channel_number as an input to the delete function too, so it would turn into this: (where ucn is the user_channel_number)
def delete_events(self, ucn):
if ucn == True:
print 'The program number is correct and will be deleted'
# action = 'DeleteEvent'
menu_action = 'all'
book = 'RECYC:687869882'
arg_list = [('C:\\Users\\yke01\\Documents\\StormTest\\Scripts\\Completed'
'\\Utils\\UPNP_Client_Cmd_Line.py')]
arg_list.append(' --action=')
arg_list.append(action)
arg_list.append(' --ip=')
arg_list.append('10.10.8.89')
arg_list.append(' --objectId=')
arg_list.append(book)
subprocess.call(["python", arg_list])
print 'The program deleted successfully'
I have also changed `return 'The program number is correct and will be deleted'' to a print statement as I have a feeling the return would end the function before the other lines of code would be run
So the code would probably end up being something like:
user_channel_number = check_channel_number()
delete_events(user_channel_number)
EDIT:
just noticed it looks like your functions are part of a class,
in that case, you could do:
self.ucn = self.check_channel_number()
self.delete_events(self.ucn)
(or if you dont want to pass the user_channel_number into the function you could change if user_channel_number: to if self. user_channel_number:

Printing an object python class

I wrote the following program:
def split_and_add(invoer):
rij = invoer.split('=')
rows = []
for line in rij:
rows.append(process_row(line))
return rows
def process_row(line):
temp_coordinate_row = CoordinatRow()
rij = line.split()
for coordinate in rij:
coor = process_coordinate(coordinate)
temp_coordinate_row.add_coordinaterow(coor)
return temp_coordinate_row
def process_coordinate(coordinate):
cords = coordinate.split(',')
return Coordinate(int(cords[0]),int(cords[1]))
bestand = file_input()
rows = split_and_add(bestand)
for row in range(0,len(rows)-1):
rij = rows[row].weave(rows[row+1])
print rij
With this class:
class CoordinatRow(object):
def __init__(self):
self.coordinaterow = []
def add_coordinaterow(self, coordinate):
self.coordinaterow.append(coordinate)
def weave(self,other):
lijst = []
for i in range(len(self.coordinaterow)):
lijst.append(self.coordinaterow[i])
try:
lijst.append(other.coordinaterow[i])
except IndexError:
pass
self.coordinaterow = lijst
return self.coordinaterow
However there is an error in
for row in range(0,len(rows)-1):
rij = rows[row].weave(rows[row+1])
print rij
The outcome of the print statement is as follows:
[<Coordinates.Coordinate object at 0x021F5630>, <Coordinates.Coordinate object at 0x021F56D0>]
It seems as if the program doesn't acces the actual object and printing it. What am i doing wrong here ?
This isn't an error. This is exactly what it means for Python to "access the actual object and print it". This is what the default string representation for a class looks like.
If you want to customize the string representation of your class, you do that by defining a __repr__ method. The typical way to do it is to write a method that returns something that looks like a constructor call for your class.
Since you haven't shown us the definition of Coordinate, I'll make some assumptions here:
class Coordinate(object):
def __init__(self, x, y):
self.x, self.y = x, y
# your other existing methods
def __repr__(self):
return '{}({}, {})'.format(type(self).__name__, self.x, self.y)
If you don't define this yourself, you end up inheriting __repr__ from object, which looks something like:
return '<{} object at {:#010x}>'.format(type(self).__qualname__, id(self))
Sometimes you also want a more human-readable version of your objects. In that case, you also want to define a __str__ method:
def __str__(self):
return '<{}, {}>'.format(self.x, self.y)
Now:
>>> c = Coordinate(1, 2)
>>> c
Coordinate(1, 2)
>>> print(c)
<1, 2>
But notice that the __str__ of a list calls __repr__ on all of its members:
>>> cs = [c]
>>> print(cs)
[Coordinate(1, 2)]

Categories