我正在重新组织我的代码,从而创建新的命名空间.我正在为模块更改"静态"类(每种方法中带有@staticmethod的类).这是要走的路,对吧?
问题是我对如何在这些模块之间共享资源有疑问.
假设我有一个模块,我从中与数据库建立了所有连接,当然所有类/方法都共享存储数据库游标的变量(我使用的是SQLite).现在,在不同的模块中,他们还必须共享光标.

所以,我的想法:
在每个模块中声明全局变量.但全球化是邪恶的,吃孩子并偷走我们的工作.所以我不知道这是不是要走的路.
'''Sub Module 1'''
global database_cursor
Run Code Online (Sandbox Code Playgroud)使用原始database_cursor导入"father"database_module并使用如下内容:
'''Sub Module 1'''
db_cursor = database_module.database_cursor
Run Code Online (Sandbox Code Playgroud)在这种情况下,第二个看起来很好,但我认为在许多情况下会导致递归导入,我想这是要避免的.
昨晚,我正在编写一些娱乐代码,并且在某些时候我更换了一个concatMap,>>=并且在我的代码中看到了大约10%的加速.
我的印象是对于>>=for 的定义[]是完全正确的concatMap,所以我有点困惑.
我试图对setParentPython中的一个对象(一个继承自不同类的类的实例 - 具体而言QtGui.QLabel)执行一些操作(),但是在运行时期间引发了上述错误.对象本身有一些具有实际内容的字段(在调试时验证),但由于某种原因我无法"使用"它.错误意味着什么,我该如何解决?对于一些其他信息,我会说在我尝试对它执行此操作之前,该对象是从静态方法返回的.
子类具有__init__()自己的功能:
def __init__(self, image, father):
super(AtomicFactory.Image, self).__init__(father)
self.raw_attributes = image.attributes
self.attributes = {}
father.addChild(self)
self.update()
Run Code Online (Sandbox Code Playgroud)
现在我写了一个类似的代码,一个简单的代码,widget.setParent(mw)当窗口移动时在行上有相同的错误.
#!/usr/bin/env python
import sys
import copy
from PyQt4 import QtCore, QtGui
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
main_widget=QtGui.QWidget()
widget = QtGui.QPushButton('Test')
widget.resize(640, 480)
widget.setParent(main_widget)
widget.move(0, 0)
widget2=QtGui.QPushButton('Test2')
widget2.i=0
widget2.resize(600, 200)
widget2.setParent(main_widget)
widget2.move(640, 0)
def onResize(event):
print event
mw=copy.deepcopy(main_widget)
widget.setParent(mw)
widget2.setParent(mw)
widget.move(0, 0)
widget2.move(640, 480)
main_widget_width=main_widget.width()
widget_width=widget.width()
width2=main_widget_width-widget_width
height2=widget2.height()
widget2.resize(width2, height2)
widget2.move(640, 0) …Run Code Online (Sandbox Code Playgroud) 我有以下3个测试.前两个工作,最后一个没有.我提出这个问题的动机是,我希望能够抛出对象A,使它与对象具有相同的类B,当A知道它是一个子类型时B.
@Test
public void testWorks() {
Object bar = "foobar";
String blah = (String) bar;
System.out.println(blah); // Outputs foobar
}
@Test
public void testAlsoWorks() {
Object bar = "helloworld";
String blah = String.class.cast(bar);
System.out.println(blah); // Outputs helloworld
}
@Test
public void testfails() {
Object bar = "foobar";
String thetype = "hello";
Class stringclass = thetype.getClass();
String blah = stringclass.cast(bar); // Compiler error: incompatible types: Object cannot be converted to String
System.out.println(blah);
} …Run Code Online (Sandbox Code Playgroud) 我按照http://nbviewer.ipython.org/github/jvns/pandas-cookbook/blob/v0.1/cookbook/Chapter%205%20-%20Combining%20dataframes%20and%20scraping%20Canadian%20weather%上的教程进行操作20data.ipynb
我有一个熊猫数据帧
weather_mar2012['Temp (°C)']
Out[30]:
Date/Time
2012-03-01 00:00:00 -5.5
2012-03-01 01:00:00 -5.7
2012-03-01 02:00:00 -5.4
Run Code Online (Sandbox Code Playgroud)
当试图绘制它我得到一个错误
weather_mar2012['Temp (°C)'].plot(figsize=(15, 5))
---------------------------------------------------------------------------
ValueError Traceback (most recent call last) <ipython-input-31-21c79ba7d5ef> in <module>()
----> 1 weather_mar2012['Temp (°C)'].plot(figsize=(15, 5))
/home/vagrant/anaconda3/lib/python3.4/site-packages/pandas/tools/plotting.py in plot_series(data, kind, ax, figsize, use_index, title, grid, legend, style, logx, logy, loglog, xticks, yticks, xlim, ylim, rot, fontsize, colormap, table, yerr, xerr, label, secondary_y, **kwds) 2486 yerr=yerr, xerr=xerr, 2487 label=label, secondary_y=secondary_y,
-> 2488 **kwds) 2489 2490
/home/vagrant/anaconda3/lib/python3.4/site-packages/pandas/tools/plotting.py in _plot(data, x, y, …Run Code Online (Sandbox Code Playgroud) 我想将文件中的所有整数读入一个列表.所有数字由空格(一个或多个)或结束线字符(一个或多个)分隔.这样做最有效和/或最优雅的方法是什么?我有两个解决方案,但我不知道它们是否好.
检查数字:
for line in open("foo.txt", "r"):
for i in line.strip().split(' '):
if i.isdigit():
my_list.append(int(i))
Run Code Online (Sandbox Code Playgroud)处理例外情况:
for line in open("foo.txt", "r"):
for i in line:
try:
my_list.append(int(i))
except ValueError:
pass
Run Code Online (Sandbox Code Playgroud)样本数据:
1 2 3
4 56
789
9 91 56
10
11
Run Code Online (Sandbox Code Playgroud) 我有一个与轨道力学中的太阳同步共振条件有关的方程.我目前正在学习Python,所以我尝试使用以下代码在SymPy中解决它:
from sympy import symbols,solve
[n_,Re_,p_,i_,J2_,Pe_] = symbols(['n_','Re_','p_','i_','J2_','Pe_'])
del_ss = -((3*n_*(Re_**2)*J2_/(4*(p_**2)))*(4-5*(sin(i_)**2)))-((3*n_*(Re_**2)*J2_/(2*(p_**2)))*cos(i_))-((2*pi)/Pe_)
pprint(solve(del_ss,i_))
Run Code Online (Sandbox Code Playgroud)
可以为五个变量成功重新排列表达式,但是当i_在solve命令中使用变量时(如上所述),会产生错误:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python27\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 479, in runfile
execfile(filename, namespace)
File "C:\Users\Nathan\Python\sympy_test_1.py", line 22, in <module>
pprint(solve(del_ss,i_))
File "C:\Python27\lib\site-packages\sympy\solvers\solvers.py", line 484, in solve
solution = _solve(f, *symbols, **flags)
File "C:\Python27\lib\site-packages\sympy\solvers\solvers.py", line 700, in _solve
soln = tsolve(f_num, symbol)
File "C:\Python27\lib\site-packages\sympy\solvers\solvers.py", line 1143, in tsolve
"(tsolve: at least one Function expected at this point")
NotImplementedError: …Run Code Online (Sandbox Code Playgroud) 我正在尝试将迭代器作为模板参数传递给模板方法,但编译器抱怨:
error C2783: 'void Test::Assert(std::vector<T>::const_iterator)':
could not deduce template argument for 'T'
Run Code Online (Sandbox Code Playgroud)
产生错误的代码是:
#include "stdafx.h"
#include <iostream>
#include <vector>
class Test
{
public:
template <typename T>
void Assert(typename std::vector<T>::const_iterator it)
{
std::cout << *it << std::endl;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
Test test;
std::vector<double> myVec;
test.Assert(myVec.cbegin());
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我猜有一种简单的方法可以使这项工作,因为大多数std算法可以从迭代器中推断出类型.
我在HPC上管理多个模块,并希望使用pip为工具安装一些要求.
我不会使用virtualenv,因为它们与我们的模块系统不兼容.我想安装模块本地版本的软件包,并PYTHONPATH在加载模块时正确设置,当我正在安装的软件包也没有安装在默认的python环境中时,这个工作正常.
我不想做的是在安装模块本地版本时卸载默认的python版本的软件包.
例如,一个包需要numpy==1.6,并且我使用的python安装的默认版本是1.8.0.当我
pip install --install-option="--prefix=$RE_PYTHON" numpy==1.6
Run Code Online (Sandbox Code Playgroud)
哪里RE_PYTHON指向模块本地site-packages目录的顶部,numpy==1.6安装正常,然后pip继续并1.8.0从我正在使用的python树开始卸载(为什么它想要卸载更新版本超出我但我想要即使我正在进行例如本地安装,也要避免这种情况numpy==1.10.1.
如何防止pip这样做?这真的很烦人,我找不到一个不涉及virtualenv的解决方案.
鉴于此代码段:
someFunction x = print x `seq` 1
main = do print (someFunction "test")
Run Code Online (Sandbox Code Playgroud)
代码执行时为什么不print x打印test?
$./seq_test
1
Run Code Online (Sandbox Code Playgroud)
如果我替换它error我可以检查左操作数seq 是否确实被评估.
我怎样才能达到预期的输出:
test
1
Run Code Online (Sandbox Code Playgroud)
只修改someFunction?
python ×6
haskell ×2
c++ ×1
casting ×1
class ×1
deep-copy ×1
generics ×1
ghc ×1
globals ×1
io ×1
java ×1
list ×1
matplotlib ×1
module ×1
namespaces ×1
pandas ×1
performance ×1
pip ×1
pyqt ×1
seq ×1
superclass ×1
sympy ×1
template-argument-deduction ×1
templates ×1