python的类何时被加载_如何从给定的目录动态加载python类?

#!/usr/bin/env python

import os

import sys

import inspect

def load_modules_from_path(path):

"""

Import all modules from the given directory

"""

# Check and fix the path

if path[-1:] != '/':

path += '/'

# Get a list of files in the directory, if the directory exists

if not os.path.exists(path):

raise OSError("Directory does not exist: %s" % path)

# Add path to the system path

sys.path.append(path)

# Load all the files in path

for f in os.listdir(path):

# Ignore anything that isn't a .py file

if len(f) > 3 and f[-3:] == '.py':

modname = f[:-3]

# Import the module

__import__(modname, globals(), locals(), ['*'])

def load_class_from_name(fqcn):

# Break apart fqcn to get module and classname

paths = fqcn.split('.')

modulename = '.'.join(paths[:-1])

classname = paths[-1]

# Import the module

__import__(modulename, globals(), locals(), ['*'])

# Get the class

cls = getattr(sys.modules[modulename], classname)

# Check cls

if not inspect.isclass(cls):

raise TypeError("%s is not a class" % fqcn)

# Return class

return cls

def main():

load_modules_from_path('modules')

# load the TestClass1

class_name = load_class_from_name('class1.TestClass1')

# instantiate the Testclass1

obj = class_name()

# using this object obj to call the attributes inside the class

print obj.testclass1()

if __name__ == '__main__': main()

在modules目录中,我还有两个模块要测试:

^{pr2}$

[♫ test] modules cat class1.py

class TestClass1(object):

def testclass1(self):

print 'I am from testclass1'

def some_function():

print 'some function 1'

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值