【发布时间】:2020-05-05 10:21:22
【问题描述】:
我在终端外壳上运行以下代码:
>>> import Strat
>>> x=Strat.Try()
>>> x.do_something()
You can do anything here!!!(this is the output of do_something)
但同一个文件在文件中调用时不起作用:
import Strat
class Strategy:
def gen_fibonacci(self,ind,n):
x=Strat.Try()
x.do_something()
l=[]
num = 3
t1 = 0
t2 = 1
nextTerm = 0
i=1
if ind==1:
l.append(0)
l.append(1)
i=3
if ind==2:
l.append(1)
i=2
while i<n:
nextTerm=t1+t2
t1=t2
t2=nextTerm
if num>=ind:
i=i+1
l.append(nextTerm)
num=num+1
return l
代码给出以下错误:
Traceback (most recent call last):
File "./python_plugins/strat1.py", line 8, in gen_fibonacci
x=Strat.Try()
AttributeError: module 'Strat' has no attribute 'Try'
注意:这里的 Strat 是一个共享库(so 文件),类尝试使用成员函数 do_something()
strat.so 文件是 :
的编译版本namespace python = boost::python;
class Strat
{
public:
virtual std::vector<long long> gen_fibonacci(int in,int n)= 0;
};
struct Try
{
void do_something()
{
std::cout<<"You can do anything here!!!"<<"\n";
}
};
class PyStrat final
: public Strat
, public bp::wrapper<Strat>
{
std::vector<long long> gen_fibonacci(int in,int n) override
{
get_override("gen_fibonacci")();
}
};
BOOST_PYTHON_MODULE(Strat)
{
bp::class_<Try>("Try")
.def("do_something", &Try::do_something)
;
bp::class_<std::vector<long long> >("Long_vec")
.def(bp::vector_indexing_suite<std::vector<long> >())
;
bp::class_<PyStrat, boost::noncopyable>("Strat")
.def("gen_fibonacci", &Strat::gen_fibonacci)
;
}
编译使用的命令:
g++ -I /usr/include/python3.6 -fpic -c -o Strat.o strat_helper.cpp
g++ -o Strat.so -shared Strat.o -L/usr/lib/x86_64-linux-gnu -lboost_python3-py36 -lpython3.6m
我正在使用 boost python。
【问题讨论】:
-
您的代码中是否还有其他文件名
Strat.py? -
@ThierryLathuille 不,只有一个目标文件strat.o,我不认为这是一个问题,因为覆盖
gen_fibonacci函数发生得很好,此外,如果我删除这两行代码可以工作很好 -
检查两种情况下导入的文件:
import Strat; print(Strat.__file__) -
我检查了两个导入相同的文件:Strat.so
-
和来自同一个目录?
标签: python python-3.x python-import attributeerror boost-python