Python 如何插入一些“;“行”;从另一个脚本到主脚本

Python 如何插入一些“;“行”;从另一个脚本到主脚本,python,import,refactoring,Python,Import,Refactoring,假设我有这个脚本: from bokeh.plotting import figure, show, output_file p = figure() p.circle([1,2,3], [4,5,6]) p.title.text = "Title" p.title.text_color = "Orange" p.title.text_font = "times" show(p) output_file("file.html") 我想在其他脚本中重用第4行到第6行,而不必在每个脚本中复制和粘贴

假设我有这个脚本:

from bokeh.plotting import figure, show, output_file
p = figure()
p.circle([1,2,3], [4,5,6])
p.title.text = "Title"
p.title.text_color = "Orange"
p.title.text_font = "times"
show(p)
output_file("file.html")
我想在其他脚本中重用第4行到第6行,而不必在每个脚本中复制和粘贴它们

如果我将第4-6行放在一个单独的.py文件中,然后将该文件导入到主脚本中,那么未定义的“p”对象将出现名称错误

重用这些行的正确方法是什么?

使用函数

# in settitle.py
def set_title(p):
    p.title.text = "Title"
    p.title.text_color = "Orange"
    p.title.text_font = "times"
然后像这样导入函数

from settitle import set_title
和使用

from settitle import set_title
from bokeh.plotting import figure, show, output_file
p = figure()
p.circle([1,2,3], [4,5,6])
set_title(p)
show(p)
output_file("file.html")
使用函数

# in settitle.py
def set_title(p):
    p.title.text = "Title"
    p.title.text_color = "Orange"
    p.title.text_font = "times"
然后像这样导入函数

from settitle import set_title
和使用

from settitle import set_title
from bokeh.plotting import figure, show, output_file
p = figure()
p.circle([1,2,3], [4,5,6])
set_title(p)
show(p)
output_file("file.html")