How to define decorator within the class? - python

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)

Related

Why is the return function not passing the variables to the next function?

I'm trying to get rid of the error without moving the input function out of the userInput function. I expected the return function to remove the NameError. I looked all over stack exchange and in my textbook to figure out this problem.
def userInput():
a = float(input("Enter a: "))
b = float(input("Enter b: "))
return (a,b)
def printFunction(a2,b2):
print(a2)
print(b2)
def main():
userInput()
printFunction(a2,b2)
main()
NameError: name 'a2' is not defined
Functions return values, not variables. The names a and b are only defined in userInput: you need to receive the values returned by userInput in variables defined in main.
def main():
x, y = userInput()
Printfunction(x, y)
You need to assign the return values of userInput to variables if you want to be able to refer to them on the next line:
def main():
a2, b2 = userInput()
Printfunction(a2,b2)
or you could skip a step and pass userInput's output directly to Printfunction as positional arguments with the * operator:
def main():
Printfunction(*userInput())

How to run a specific function using a code within python [duplicate]

I am trying to use functional programming to create a dictionary containing a key and a function to execute:
myDict={}
myItems=("P1","P2","P3",...."Pn")
def myMain(key):
def ExecP1():
pass
def ExecP2():
pass
def ExecP3():
pass
...
def ExecPn():
pass
Now, I have seen a code used to find the defined functions in a module, and I need to do something like this:
for myitem in myItems:
myDict[myitem] = ??? #to dynamically find the corresponding function
So my question is, How do I make a list of all the Exec functions and then assign them to the desired item using the a dictionary? so at the end I will have myDict["P1"]() #this will call ExecP1()
My real problem is that I have tons of those items and I making a library that will handle them so the final user only needs to call myMain("P1")
I think using the inspect module, but I am not so sure how to do it.
My reason to avoid:
def ExecPn():
pass
myDict["Pn"]=ExecPn
is that I have to protect code as I am using it to provide a scripting feature within my application.
Simplify, simplify, simplify:
def p1(args):
whatever
def p2(more args):
whatever
myDict = {
"P1": p1,
"P2": p2,
...
"Pn": pn
}
def myMain(name):
myDict[name]()
That's all you need.
You might consider the use of dict.get with a callable default if name refers to an invalid function—
def myMain(name):
myDict.get(name, lambda: 'Invalid')()
(Picked this neat trick up from Martijn Pieters)
Simplify, simplify, simplify + DRY:
tasks = {}
task = lambda f: tasks.setdefault(f.__name__, f)
#task
def p1():
whatever
#task
def p2():
whatever
def my_main(key):
tasks[key]()
Not proud of it, but:
def myMain(key):
def ExecP1():
pass
def ExecP2():
pass
def ExecP3():
pass
def ExecPn():
pass
locals()['Exec' + key]()
I do however recommend that you put those in a module/class whatever, this is truly horrible.
If you are willing to add a decorator for each function, you can define a decorator which adds each function to a dictionary:
def myMain(key):
tasks = {}
def task(task_fn):
tasks[task_fn.__name__] = task_fn
#task
def ExecP1():
print(1)
#task
def ExecP2():
print(2)
#task
def ExecP3():
print(3)
#task
def ExecPn():
print(4)
tasks['Exec' + key]()
Another option is to place all the functions under a class (or in a different module) and use getattr:
def myMain(key):
class Tasks:
def ExecP1():
print(1)
def ExecP2():
print(2)
def ExecP3():
print(3)
def ExecPn():
print(4)
task = getattr(Tasks, 'Exec' + key)
task()
# index dictionary by list of key names
def fn1():
print "One"
def fn2():
print "Two"
def fn3():
print "Three"
fndict = {"A": fn1, "B": fn2, "C": fn3}
keynames = ["A", "B", "C"]
fndict[keynames[1]]()
# keynames[1] = "B", so output of this code is
# Two
You can just use
myDict = {
"P1": (lambda x: function1()),
"P2": (lambda x: function2()),
...,
"Pn": (lambda x: functionn())}
myItems = ["P1", "P2", ..., "Pn"]
for item in myItems:
myDict[item]()
This will call methods from dictionary
This is python switch statement with function calling
Create few modules as per the your requirement.
If want to pass arguments then pass.
Create a dictionary, which will call these modules as per requirement.
def function_1(arg):
print("In function_1")
def function_2(arg):
print("In function_2")
def function_3(fileName):
print("In function_3")
f_title,f_course1,f_course2 = fileName.split('_')
return(f_title,f_course1,f_course2)
def createDictionary():
dict = {
1 : function_1,
2 : function_2,
3 : function_3,
}
return dict
dictionary = createDictionary()
dictionary[3](Argument)#pass any key value to call the method
#!/usr/bin/python
def thing_a(arg=None):
print 'thing_a', arg
def thing_b(arg=None):
print 'thing_b', arg
ghetto_switch_statement = {
'do_thing_a': thing_a,
'do_thing_b': thing_b
}
ghetto_switch_statement['do_thing_a']("It's lovely being an A")
ghetto_switch_statement['do_thing_b']("Being a B isn't too shabby either")
print "Available methods are: ", ghetto_switch_statement.keys()
Often classes are used to enclose methods and following is the extension for answers above with default method in case the method is not found.
class P:
def p1(self):
print('Start')
def p2(self):
print('Help')
def ps(self):
print('Settings')
def d(self):
print('Default function')
myDict = {
"start": p1,
"help": p2,
"settings": ps
}
def call_it(self):
name = 'start'
f = lambda self, x : self.myDict.get(x, lambda x : self.d())(self)
f(self, name)
p = P()
p.call_it()
class CallByName():
def method1(self):
pass
def method2(self):
pass
def method3(self):
pass
def get_method(self, method_name):
method = getattr(self, method_name)
return method()
callbyname = CallByName()
method1 = callbyname.get_method(method_name)
```
def p1( ):
print("in p1")
def p2():
print("in p2")
myDict={
"P1": p1,
"P2": p2
}
name=input("enter P1 or P2")
myDictname
You are wasting your time:
You are about to write a lot of useless code and introduce new bugs.
To execute the function, your user will need to know the P1 name anyway.
Etc., etc., etc.
Just put all your functions in the .py file:
# my_module.py
def f1():
pass
def f2():
pass
def f3():
pass
And use them like this:
import my_module
my_module.f1()
my_module.f2()
my_module.f3()
or:
from my_module import f1
from my_module import f2
from my_module import f3
f1()
f2()
f3()
This should be enough for starters.

Explain how probSecond.calls equal to zero

def MainCount(f):
def progFirst(*args,**kwargs):
progFirst.calls+=1
return f(*args,**kwargs)
progFirst.calls=0
return progFirst
#MainCount
def progSecond(i):
return i+1
#MainCount
def Count(i=0,j=1):
return i*j+1
print(progSecond.calls)
for n in range(5):
progSecond(n)
Count(j=0,i=1)
print(Count.calls)
Output :0
1
As per my understanding MainCount(probSecond) but I am not understant then how probSecond.calls equal to zero same in Count.calls also
As You Can See in MainCount function probFirst.Calls is attribute of function .When MainCount(probSecond) Now probSecond.calls is also attribute of MainCount function.
# A Python example to demonstrate that
# decorators can be useful attach data
# A decorator function to attach
# data to func
def attach_data(func):
func.data = 3
return func
#attach_data
def add (x, y):
return x + y
# Driver code
# This call is equivalent to attach_data()
# with add() as parameter
print(add(2, 3))
print(add.data)

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

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.

Propagating a variable defined under a function (under a particular Class) to some other function under the same Class

I have a code which has few Classes in it. Under SecondClass, there is a function called plot_image. Under this function, there are three variables defined called my_x, my_y, my_z. I am trying to make these variables accessible inside some other function called get_histogram in the same Class. Here is a non-working example in the form of a pseudo-snippet:
import some_modules_in_here #these are required for classes below
#===================================================================================================
# utility
#===================================================================================================
class FirstClass(something.something.SayClass):
def file1(self, some_arguments):
pros = do_something
return pros
#===================================================================================================
# visualize
#===================================================================================================
class SecondClass(something.something.SayClass):
def plot_image(self, some_parameter):
if some_parameter is not None:
my_x = some_value1
my_y = some_value2
my_z = some_value3
def get_histogram(self, some_parameter, some_other_parameter, return_info):
if '3d' in some_parameter:
do_this
else:
do_that
if some_other_parameter:
calculate_something
if return_info:
for k, l, m in zip(my_x, my_y, my_z):
do_some_stuff
print(something_in_here)
return_value = do_something_else_in_here
return return_value
.
.
.
def print_values(self):
'''
write some values of image to file.
'''
Second = SecondClass()
I tried the keyword global at the top of the function plot_image but that doesn't do the job for me giving error message:
"NameError: Name 'my_x' is not defined."
What is the solution?

Categories