简体   繁体   中英

How I could turn this Python code into a function?

I have this code that I want to turn into a function. I need function_text to be accessible outside the function.

   function_text = TextClip(item_1, fontsize=main_text_size, font=main_font, color=corner_text_color, size=(w, text_size_60))
   function_text = function_text.set_fps(fps)
   function_text = function_text.set_duration(5)
   function_text = function_text.margin(left=0, right=1300, top=950, opacity=0)
   function_text = function_text.set_position(("center"))

I want to be able to enter a variable name(function_text), and margin attribute with values to that variable(4th line in the code)

This is where I am at right now:

def displayText(my_str):
   global my_str
   my_str = TextClip(item_1, fontsize=main_text_size, font=main_font, color=corner_text_color, size=(w, text_size_60))
   my_str = my_str.set_fps(fps)
   my_str = my_str.set_duration(5)
   my_str = my_str.margin(left=0, right=1300, top=950, opacity=0)
   my_str = my_str.set_position(("center"))
   return
displayText("function_text")

The problem I get is that I can't set my parameter as global because I get this error:

SyntaxError: name 'my_str' is parameter and global

You're trying to use my_str as both a global variable and a paramater. You can only use it one way. From your code it looks like you don't actually need to read in my_str (in the first line of the function you assign to it a new value), so returning it should suffice:

def displayText():
   my_str = TextClip(item_1, fontsize=main_text_size, font=main_font, color=corner_text_color, size=(w, text_size_60))
   my_str = my_str.set_fps(fps)
   my_str = my_str.set_duration(5)
   my_str = my_str.margin(left=0, right=1300, top=950, opacity=0)
   my_str = my_str.set_position(("center"))
   return my_str
function_text = displayText()

Try not to use global variables (ever). The error is because you set the same name for your global variable and for your parameter name, both are 'my_str'.

def displayText( my_str ):

And then inside of the function, where my_str already exist because it was passed as a parameter, you are defining my_str again, this is wrong as it already was defined previously.

just delete

global my_str

and add:

return my_str

at the end of the function

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM