每一个python脚本文件都可以被当成是一个模块,一个模块可以包含直接运行的代码块、类定义、函数定义或者几个的组合。
下面举例模块里是一个类定义,然后这个模块怎么被调用import
FooClass.py源文件如下:
#!usr/local/bin/python
class FooClass(object):
"""my very first class: FooClass"""
version = 0.1 # class (data) attribute
def __init__(self, nm='John Doe'):
"""constructor"""
self.name = nm # class instance (data) attribute
print 'Created a class instance for', nm
def showname(self):
"""display instance attribute and class name"""
print 'Your name is', self.name
print 'My name is', self.__class__.__name__
def showver(self):
"""display class(static) attribute"""
print self.version # references FooClass.version
def addMe2Me(self, x): # does not use 'self'
"""apply + operation to argument"""
return x + x
将这个源文件发在d;盘中,如果我们直接import FooClass会提示:
no module named FooClass。
可以通过sys模块添加路径。
python的搜索路径被保存在sys模块的sys.path中,sys.path就是一个路径列表,模块必须放在其中一个路径中才能够被导入,本例中的FooClass模块在d盘中,所以要用sys.path.append对这个路径列表进行修改,直接在列表后面追加一个’d:’就可以了;
这样就可以直接导入了
然后就可以直接使用模块中的函数或者类属性,但是在构建一个实体时,出现
‘module’object is not callable。
意思将”FooClass”这个模块作为一个函数来调用,但是它却无法调用;
所以为了正确表示,使用模块.构建函数 的格式:
foo1=FooClass.FooClass()就可以成功了