这段时间在学习python , 关于python import 调用包,模块,类,函数 方面有点模糊,搜了一些资料,转来学习一下,也供以后参考。。。
众所周知,python既可以导入包(import package),也可以导入模块(import module),package一般理解为多文件的模块,它是这样定义的,如果一个目录下存在”init.py”这个文件,那么python就认为这个目录下的所有文件同属于一个package(这和java的namespace有点像,但是java可不需要这么个特殊文件),如果没有这个文件,那么python认为目录下的py文件都是不相干的独立模块。但是在子目录中你可不能这么干,如果子目录中没有”init.py”,那么该目录下的程序算是白写了,根本没有办法引用。当然,也不是绝对的,除非绕个大弯儿:设置当前目录,然后导入,然后重设当前目录。比如,程序需要使用test目录中的模块,而test目录不是package,你只能这样做:
1: os.chdir(“test”)
2: import testfuncs
3: os.chdir(“..”)
最方便的引入,当然是同一个目录的模块(除了及其简单的程序,很少有人会使用这种扁平的目录结构),那是想怎么导入就怎么导入。比如在主程序中想要使用另一个文件模块中的函数,只需要直接导入即可:
1: import testfuncs #直接导入模块(也就是不带扩展名的文件名)
2:
3: testfuncs.nousefunc() #通过模块的名字引用其中的函数
4: from testfuncs import nousefunc #导入模块中的函数
5: nousefunc() #直接调用导入的函数
上面只是最简单的情况,如果文件中定义的是class怎么样呢,实际使用也是差不多的,不过要多一次构造class的实例的调用:
1: import testclass #直接导入模块(也就是不带扩展名的文件名)
2: obj=testclass.TestClass(); #实例化类
3: obj.func1() #通过模块的名字引用其中的class,然后才到类的函数,注意类要实例化
4: from testclass import TestClass #导入模块中的类
5: obj=TestClass(); #实例化类
6: obj.func1() #调用函数
如果都是这种从程序中引入同目录或者子目录的包,那么事情就简单了,但是如果是同为子目录中的模块,要引入兄弟目录中的模块或类,要怎么办呢?例如,如下的目录结构:
图中src目录就是程序的顶层目录,也是包导入的顶层package,pub目录及其子目录是公用程序所在。在这种情况下,最好的方法就是在主程序中(一般位于应用的源程序的根目录,如图中的start.py),把所有下级的目录都缴入的sys.path中,然后在子目录中的模块中,只要使用完全限定的包名引入其他子目录中的模块或者类就可以了。然而现实的情况往往不那么尽如人意,比如为公用包写的测试程序需要放在pub/test目录下,测试目标在pub/data目录下,这是不能寄希望与应用的主程序了,因为此时不会去运行应用程序。这种情况下,启动程序和被引用的包同在一个父目录的子目录中。此时该怎么办呢,还是老办法,要把父目录(src/pub)和(src/pub/data、src/pub/test)目录都要加入sys.path中,然后再用
绝对的方式进行引入(import pub.data.datautil / from pub.data.datautil import DataUtil)。每一个需要的模块都要这么干,因此,我特地写了一个函数,来自动的处理这种情况:
import os,sys
import TestClass
import testfuncs;
from TestClass import TestClass;
def _prepareRelativeImport(layer=2):
“”” 为相对引用做准备,以便下层目录中的模块,相对引用[本目录]以及[父目录]和[兄弟目录]中的模块。
参数layer,表示引入到多少层父目录。默认为2->引入本目录和父目录;3->引入本目录、父目录和祖父目录。
“””
import sys,os;
curP=os.path.abspath(os.path.dirname(file)); oriP=curP;package=curP.rpartition(os.path.sep)[2];
print(‘\r\ncurdir=’,curP);
while layer>=0:
layer-=1;
if not curP in sys.path:sys.path.append(curP);
pa=curP.rpartition(os.path.sep);curN=pa[2];pp=pa[0];os.chdir(pp);
if ‘init‘ in ”.join(os.listdir(curP)):import(curN);
curP=pp;
os.chdir(oriP);
if name==’main‘:
if not ‘file‘ in dir():file=os.path.abspath(‘.’)+os.path.sep+”1.py”;
_prepareRelativeImport(2)
from TestClass import TestClass;
from pub.test.TestClass import TestClass;
from pub.data.CompareOperator import CompareOperators
print(‘\r\nTest of RelativeImport done!’)
总结,这么做之后解决了对于测试单个功能或模块的导入问题,但是在从应用的顶层目录中运行程序时,还是只能使用Python 3的”from .”来做相对导入,这还真是纠结。
I am also commenting to let you be aware of what a fine discovery my daughter experienced viewing your web page. She discovered a lot of things, not to mention what it is like to possess an ideal coaching character to get others smoothly understand certain specialized subject matter. You actually surpassed our own expected results. Thank you for offering such productive, trustworthy, educational not to mention easy guidance on that topic to Mary.
I was suggested this website by my cousin. I am not sure whether this
post is written by him as no one else know such detailed about my difficulty.
You are amazing! Thanks!
I wish to voice my love for your generosity supporting persons who should have assistance with that content. Your special commitment to passing the solution across turned out to be unbelievably invaluable and have regularly made guys just like me to attain their desired goals. Your own important tips and hints entails a whole lot to me and much more to my mates. Regards; from all of us.
I simply needed to thank you very much once again. I’m not certain the things I could possibly have tried without these tricks shared by you directly on this field. It was before a real challenging case in my position, but witnessing this well-written approach you resolved that took me to cry for joy. I will be happier for this assistance and thus hope that you know what a powerful job you were getting into educating the rest through the use of your websites. More than likely you haven’t got to know all of us.
I simply desired to thank you very much again. I’m not certain the things that I might have created without these tips and hints provided by you directly on my theme. This has been an absolute horrifying condition for me personally, nevertheless being able to see a new well-written mode you treated that made me to weep with delight. I will be happier for this support and thus hope you comprehend what an amazing job you are putting in teaching some other people through the use of your web blog. More than likely you haven’t met all of us.
[url=http://phenergan.cyou/]phenergan over the counter usa[/url]
[url=https://finasteride.digital/]propecia pills buy[/url]
My husband and i ended up being now joyous Ervin could round up his survey by way of the precious recommendations he acquired while using the web pages. It’s not at all simplistic to simply continually be offering facts which the others may have been making money from. And now we remember we now have you to thank for that. All the illustrations you have made, the simple web site menu, the friendships you can make it possible to instill – it’s got everything impressive, and it is aiding our son in addition to us imagine that that idea is entertaining, and that is extremely indispensable. Thanks for all!
I want to express my affection for your kind-heartedness supporting women who should have assistance with your theme. Your real dedication to getting the solution along appears to be remarkably functional and has made folks much like me to arrive at their endeavors. Your personal valuable help denotes a great deal to me and extremely more to my fellow workers. Regards; from all of us.
My wife and i got so fulfilled Albert could round up his reports through your ideas he gained from your own weblog. It is now and again perplexing to simply always be giving out points that many many people could have been making money from. And we consider we’ve got the writer to thank for this. Most of the explanations you made, the easy blog navigation, the friendships you will aid to instill – it is all sensational, and it’s helping our son and our family reason why that issue is entertaining, and that’s quite important. Thanks for the whole thing!
Thanks a lot for giving everyone an extremely spectacular opportunity to read in detail from this website. It is usually very nice and as well , full of a lot of fun for me and my office fellow workers to search the blog at minimum 3 times per week to study the fresh guidance you have. And lastly, we’re usually satisfied for the beautiful information you give. Selected two areas in this post are essentially the most efficient I have had.
I and also my guys happened to be going through the nice procedures from your website and quickly developed an awful suspicion I had not expressed respect to the blog owner for those tips. My guys happened to be totally happy to see all of them and already have honestly been taking advantage of them. Thank you for turning out to be very kind as well as for figuring out these kinds of incredible subjects millions of individuals are really desperate to understand about. Our own sincere apologies for not expressing appreciation to sooner.
I would like to show thanks to this writer for bailing me out of this type of difficulty. As a result of scouting through the world-wide-web and getting views which are not helpful, I figured my life was over. Living minus the approaches to the difficulties you have sorted out through your good posting is a crucial case, and those that could have in a negative way damaged my career if I had not discovered your blog. Your own training and kindness in handling everything was useful. I don’t know what I would have done if I hadn’t come across such a subject like this. I can at this point look forward to my future. Thanks very much for your professional and effective guide. I will not be reluctant to recommend your web blog to any individual who will need direction on this matter.
I want to show my passion for your kind-heartedness giving support to folks that need help with that concern. Your special dedication to getting the solution up and down appeared to be really productive and have all the time made guys like me to attain their aims. Your personal warm and helpful advice means a whole lot a person like me and a whole lot more to my office workers. Best wishes; from each one of us.
I together with my friends have already been reviewing the best tactics on the website and then then got a horrible feeling I had not thanked the website owner for them. Those boys had been certainly thrilled to read through all of them and have in effect seriously been tapping into these things. We appreciate you actually being indeed considerate and then for picking these kinds of notable issues millions of individuals are really desperate to be aware of. Our own honest regret for not saying thanks to earlier.
I and also my friends ended up following the good helpful tips on your site and then unexpectedly I had an awful suspicion I had not thanked the site owner for those techniques. All the guys happened to be for that reason warmed to learn them and now have simply been enjoying them. Thank you for really being quite considerate and also for picking these kinds of smart subjects most people are really needing to know about. Our sincere apologies for not expressing gratitude to earlier.
[url=https://levitra.cfd/]vardenafil india online[/url]
I want to express some thanks to the writer just for bailing me out of this dilemma. Right after checking throughout the online world and getting ideas which were not helpful, I was thinking my life was over. Being alive minus the approaches to the problems you’ve solved through your entire report is a critical case, as well as those which could have adversely affected my entire career if I hadn’t discovered your web page. Your good know-how and kindness in playing with every aspect was very helpful. I am not sure what I would’ve done if I hadn’t come across such a subject like this. I can at this point look forward to my future. Thanks for your time very much for this high quality and sensible help. I will not think twice to propose your web sites to any individual who wants and needs tips about this matter.
[url=http://vardenafil.directory/]price of vardenafil[/url]
My spouse and i were really ecstatic that Edward managed to round up his research from your precious recommendations he made when using the web site. It’s not at all simplistic to simply find yourself giving out tricks which often other people may have been selling. So we realize we need the website owner to be grateful to because of that. Most of the explanations you made, the straightforward website menu, the relationships you make it possible to instill – it’s got mostly remarkable, and it’s really aiding our son and the family understand this idea is fun, which is seriously mandatory. Thanks for all!
My brother recommended I would possibly like this blog. He was
once totally right. This post actually made my day. You cann’t believe just how much time I
had spent for this information! Thank you!
Hi to all, for the reason that I am genuinely keen of reading this web
site’s post to be updated daily. It includes fastidious stuff.
I’d like to find out more? I’d love to find out
more details.
I and my friends have been reviewing the good techniques found on your site and then instantly came up with an awful suspicion I had not thanked the web blog owner for those secrets. Those ladies ended up totally happy to learn them and have in effect clearly been enjoying them. Thanks for indeed being very thoughtful and for deciding on some good subjects most people are really wanting to be informed on. My personal sincere apologies for not expressing gratitude to you earlier.
I wish to express some appreciation to you just for bailing me out of such a challenge. Because of surfing throughout the internet and getting strategies that were not powerful, I assumed my entire life was done. Living without the presence of answers to the issues you’ve solved by way of your good posting is a crucial case, and the kind that could have badly affected my entire career if I had not come across your site. Your personal know-how and kindness in playing with every item was valuable. I am not sure what I would’ve done if I hadn’t come upon such a thing like this. It’s possible to at this time look ahead to my future. Thanks very much for your reliable and amazing guide. I will not be reluctant to recommend the sites to any person who should receive counselling on this area.
I precisely desired to thank you very much all over again. I’m not certain what I would’ve created in the absence of those basics shown by you over that area of interest. It truly was a depressing scenario for me personally, but spending time with this specialized tactic you resolved it made me to jump for joy. Now i am grateful for your help and thus wish you are aware of a powerful job you have been providing educating the mediocre ones via your web site. I’m certain you haven’t come across all of us.
I needed to post you one little bit of note to be able to say thanks a lot again for your personal incredible basics you’ve featured on this site. This is simply surprisingly generous with people like you to deliver easily what exactly a few people could have offered for sale as an ebook to generate some profit for themselves, mostly considering the fact that you might well have tried it in the event you considered necessary. These tips additionally served like a good way to understand that many people have a similar dream like my very own to figure out more concerning this problem. I’m sure there are many more pleasurable moments up front for many who scan through your blog post.
My husband and i got excited that Peter managed to finish off his research while using the ideas he made from your site. It is now and again perplexing just to always be making a gift of concepts which often people might have been making money from. And we also know we have got the blog owner to appreciate because of that. The explanations you made, the easy website menu, the friendships your site make it easier to engender – it is mostly sensational, and it’s really helping our son in addition to the family consider that the article is entertaining, which is certainly incredibly indispensable. Thanks for the whole lot!
Thanks so much for providing individuals with an extremely breathtaking chance to check tips from this website. It’s always very terrific plus stuffed with fun for me personally and my office acquaintances to search the blog the equivalent of thrice a week to find out the newest items you will have. Not to mention, I am also actually contented with your unbelievable techniques served by you. Certain 3 tips in this article are indeed the most beneficial I have had.
I in addition to my pals have already been checking out the best tips located on your web blog while unexpectedly I got an awful feeling I never thanked the website owner for them. Most of the guys appeared to be absolutely joyful to study all of them and have absolutely been loving these things. Many thanks for indeed being well considerate and also for getting this sort of fine ideas most people are really desperate to learn about. Our own honest apologies for not saying thanks to you sooner.
I抎 must check with you here. Which isn’t one thing I often do! I take pleasure in reading a post that can make people think. Also, thanks for allowing me to comment!
I as well as my pals were actually looking at the great helpful tips found on your website and then unexpectedly got a horrible suspicion I had not thanked the website owner for those tips. My young boys are already for this reason thrilled to study all of them and have in effect quite simply been taking advantage of those things. Appreciate your genuinely very considerate and then for choosing this form of tremendous issues millions of individuals are really eager to discover. Our honest apologies for not expressing appreciation to you sooner.
I needed to put you this very small note to say thanks a lot yet again for all the beautiful pointers you’ve provided on this page. This is particularly open-handed of you to allow extensively what many people would’ve offered for an ebook to generate some cash on their own, certainly now that you could have done it if you decided. Those principles likewise acted like a fantastic way to be aware that other individuals have similar zeal like my own to see somewhat more when it comes to this problem. Certainly there are millions of more enjoyable occasions up front for folks who examine your site.
Insightful piece
I always learn something new from your posts. Thank you for the education!
You’ve done a fantastic job of breaking down this topic. Thanks for the clarity!
What a compelling enjoy reading! Your arguments were well-presented and convincing.
This post was a breath of fresh air. Thank you for your unique insights!
What a compelling enjoy reading! Your arguments were well-presented and convincing.
I’m amazed by the depth and b enjoy readingth of your knowledge. Thanks for sharing!
Incredibly informative post! I learned a lot and look forward to more.
You’ve done a fantastic job of breaking down this topic. Thanks for the clarity!
What a refreshing take on this subject. I completely agree with your points!
Your blog is a constant source of inspiration and knowledge. Thank you!
I’m genuinely impressed by the depth of your analysis. Great work!
You’ve opened my eyes to new perspectives. Thank you for the enlightenment!
You’ve done a fantastic job of breaking down this topic. Thanks for the clarity!
Thanks for sharing. I read many of your blog posts, cool, your blog is very good.
This was a great enjoy reading—thought-provoking and informative. Thank you!
You’ve articulated your points with such finesse. Truly a pleasure to enjoy reading.
You have a unique perspective that I find incredibly valuable. Thank you for sharing.
Incredibly informative post! I learned a lot and look forward to more.
Excellent write-up
I’m impressed by your ability to convey such nuanced ideas with clarity.
This was a thoroughly insightful enjoy reading. Thank you for sharing your expertise!
What a refreshing take on this subject. I completely agree with The points!
A constant source of inspiration and knowledge, like a muse but less mythical.
Your insights have added a lot of value to my understanding. Thanks for sharing.
I’m so glad I stumbled upon this article. It was exactly what I needed to enjoy reading!
What i do not realize is if truth be told how you are now not really a lot
more well-preferred than you might be right now. You are very intelligent.
You understand therefore significantly on the subject of this topic, produced me for my part imagine
it from numerous various angles. Its like women and men are not
fascinated except it is something to do with Girl gaga!
Your own stuffs excellent. Always care for it up!
Always learning something new here, because apparently, I didn’t pay enough attention in school.
The passion for this subject shines through The words. Inspiring!
The content is like a treasure chest; every post uncovers gems of wisdom. X marks the spot here.
I know this web page gives quality depending articles or reviews and additional data, is there any other web site which provides these kinds
of data in quality?
This is my first time pay a visit at here and i am truly pleassant
to read all at single place.
A perfect blend of informative and entertaining, like the ideal date night conversation.
I learned a lot, and now I’m curious about what else you could teach me. The intelligence is as captivating as The prose.
Reading The Writing is like finding an oasis in a desert of information. Refreshing and revitalizing.
The perspective is like a rare gem, valuable and unique in the vastness of the internet.
The piece was both informative and thought-provoking. Thanks for the great work!
You’ve presented a hard to understand topic in a clear and engaging way. Bravo!
The post added a new layer to my understanding of the subject. Thanks for sharing The knowledge.
The content is like a treasure chest; every post uncovers gems of wisdom. X marks the spot here.
The dedication to high quality content is evident. Keep up the great work!
The insights light up my intellect like fireworks. Thanks for the show!
Your article helped me a lot, is there any more related content? Thanks!
The insight and depth you bring to your posts are remarkable. Every time I read your work, I come away with a newfound understanding and appreciation for the topic. Your ability to engage and inform is a rare talent. Thank you for your valuable contributions.
Hi there, for all time i used to check website posts here in the early hours in the break of day, for the reason that i
love to gain knowledge of more and more.
Great read! The author’s perspective was fascinating and left me with a lot to think about. Let’s discuss further. Click on my nickname for more thought-provoking content!
Ridiculous story there. What occurred after? Thanks!
Excellent post. I was checking constantly this weblog and I am impressed!
Very useful information specifically the remaining phase 🙂 I
maintain such information a lot. I used to be seeking this particular info for a very
lengthy time. Thank you and good luck.
The insights dazzled me more than a candlelit dinner. Thanks for lighting up my intellect.
Excellent site. Plenty of useful information here.
I’m sending it to several pals ans also sharing in delicious.
And of course, thanks for your sweat!
If you wish for to increase your know-how just keep visiting this site and be updated with the
most up-to-date news posted here.
Hi there, just became alert to your blog through
Google, and found that it’s really informative. I’m going to watch out for
brussels. I’ll appreciate if you continue this in future.
Many people will be benefited from your writing. Cheers!
Hi, of course this paragraph is really good
and I have learned lot of things from it concerning blogging.
thanks.
Hi there, just became alert to your blog through Google, and found that it’s
truly informative. I am gonna watch out for brussels. I’ll be grateful if you continue this in future.
Many people will be benefited from your writing. Cheers!
The post added a new layer to my understanding of the subject. Thanks for sharing The knowledge.
The work is truly inspirational. It’s as if you’ve found a way to whisper sweet nothings to my intellect.
The analysis had the perfect mix of depth and clarity, like a perfectly mixed cocktail that I just can’t get enough of.
Brilliant writing! You’ve perfectly captured the essence of the topic.
I’m amazed by The knowledge, almost as much as I’m drawn to the way you present it. Share more, please?
Always excited to see The posts, like waiting for a message from a crush. Another excellent read!
I’m amazed by The knowledge, almost as much as I’m drawn to the way you present it. Share more, please?
Beautifully written and informative, making the rest of the internet look bad.
The insights are like a favorite book; I find new treasures each time I return.
Thoroughly insightful read, or so I thought until I realized it was The expertise shining through. Thanks for making me feel like a novice again!
Glad I stumbled upon this article. It’s like finding a $20 bill in a pair of old jeans.
Elegant and insightful, you tackle hard to understand issues like you’re dancing through words. Shall we dance some more?
Each article you write is like a step in a dance, moving us gracefully through The thoughts.
I must admit, The depth of analysis is as attractive as The words. Great work has never looked so good.
Consistently high-high quality content, as if you’re trying to show us all up.
What a refreshing take on this subject. I completely agree with The points!
Your point of view caught my eye and was very interesting. Thanks. I have a question for you.
Your article helped me a lot, is there any more related content? Thanks!
Реально адекватные цены на запчасти Газель в сравнении с магазинами и рынками. Отправка в регионы и доставка по городу.
Вашему вниманию представлен сайт, всё для Газели по продаже запчастей: Автофурнитуры фургона, бамперов, глушителей, инструментальных автомобильных ящиков, крыльев, рессор и амортизаторов, фар и зеркал, чехлов сидения, тентов, бортов, топливных баков, капотов, спойлеров, рессор и деталей кузова, оборудования кабины и моторного отсека, электрооборудования, узлов и деталей подвески, рамы и декоративных элементов, как навесных, так и встраиваемых в существующую базу, тормозной, выхлопной, приводной, топливной систем, а так же систем охлаждения, управления, освещения. Для удобства пользования сайтом в левом поле размещены названия разделов каталога с активным вызовом списка деталей в каталоге запчастей. На центральной части главной страницы размещены фотографии популярных изделий, названия под ними являются кнопками, нажав на них можно перейти в раздел выбранных товаров, либо к конкретному изделию. Например нажав на кнопу “Коврики Газель” вы попадете на страницу где представлен весь ассортимент ковров, декоративных консолей, подлокотников, полок и других изделий тюнинга салона. Любая ГАЗЕЛЬ запчасть найдется при помощи поиска.
Ниже фотографий размещены пронумерованные описания разделов. Описания содержат информацию необходимую для сравнения качественных характеристик деталей их особенности. Это должно помочь сделать выбор в пользу той или иной запчасти, при наличии нескольких вариантов с разными ценами,отличными характеристиками.
Thank you for your sharing. I am worried that I lack creative ideas. It is your article that makes me full of hope. Thank you. But, I have a question, can you help me?
Both informative and thought-provoking, as if my brain needed the extra workout.