从常见的python脚本

时间:2016-12-07 00:32:50

标签: python

我经常在Python中编写用于绘图的脚本,我经常想要使用图形的常用设置,包括线宽和颜色等。

目前我在文件的开头复制并粘贴所有这些变量,例如:

import matplotlib.pyplot as plt
company_color_1 = "#40A7E8"
company_color_2 = "#707070"
marker_width = 2.5


# my script here:
plt.plot(x, y, color=company_color_1)

我想要实现的是我可以在每个脚本的开头放置一行,例如:

import matplotlib.pyplot as plt
my_graph_settings()

# script:
plt.plot(x, y, color=company_color_1)

这样我就可以控制一个文件中的所有内容并更好地管理更改。

我将如何在Python中解决这个问题?

2 个答案:

答案 0 :(得分:4)

使用您想要的变量创建名为my_graph_settings.py的Python文件,然后导入它。如果您对潜在的命名冲突感到满意,并希望将每个变量用作当前脚本中定义的变量,则可以将所有内容导入当前命名空间:

import matplotlib.pyplot as plt
from my_graph_settings import *

# script:
plt.plot(x, y, color=company_color_1)

但最好别名它,这样你就不会污染名称空间:

import matplotlib.pyplot as plt
import my_graph_settings as mgs

# script:
plt.plot(x, y, color=mgs.company_color_1)

答案 1 :(得分:1)

我会考虑将其作为$('#circles').mouseenter(function(){ // Update the event handler to your 'swipeRight' event $ ('.circle').each(function(){ if (!$(this).hasClass('newClass')){ $(this).addClass('newClass'); return false; } }); }); 语句来执行,您可以在其中导入一个在其中定义了这些变量的文件。

例如:

import

在该文件import graph_config as config 中,定义要引用的属性:

graph_config.py

然后在您的脚本中,您可以引用该对象的属性:

company_color_1 = "#40A7E8"
company_color_2 = "#707070"

如果对于控制情节的其他外观非常有用,您甚至可以制作plt.plot(x, y, color=config.company_color_1) 几个属性。