python-3.x - Python 等效于 Perl 的 `$AUTOLOAD`
问题描述
正如标题所说,是否有任何与 Perl 等效的功能$AUTOLOAD
?
use strict;
use warnings;
use vars '$AUTOLOAD';
sample_function('7','11');
# AUTOLOAD() Function
sub AUTOLOAD
{
print "AUTOLOAD is set to $AUTOLOAD\n";
print "With arguments ", "@_\n";
}
输出:
AUTOLOAD is set to main::sample_function
With arguments 7 11
Python中有这样的实现吗?
解决方案
好吧,这实际上取决于您想要实现的目标。例如,对于自动加载丢失的包,您可以执行类似于此页面的操作
import os.path
try:
import some_module
except ImportError:
import pip
pip.main(['install', '--user', 'some_module'])
os.execv(__file__,sys.argv)
如果您想动态加载某些内容,您可以使用__init__.py
类似以下代码的文件(我在一些旧脚本中使用它来加载 orator 迁移模式文件)。但是,您需要import * from <whatever_folder_has_this_init_file>
:
import importlib
import inspect
import glob
from os.path import dirname, basename, isfile, join
def __get_defined_modules():
modules_path = join(dirname(__file__), "migrations", "*.py")
modules = glob.glob(modules_path)
for f in modules:
if isfile(f) and f.find('migration'):
yield basename(f)[:-3]
def run_migrations(db):
m = __get_defined_modules()
for x in m:
if x.find('migration') > -1:
module_path='{}.migrations.{}'.format(basename(dirname(__file__)), x)
for _, cls in inspect.getmembers(importlib.import_module(module_path), inspect.isclass):
if cls.__module__ == module_path:
print("Loading and executing {}: {}".format(x, cls))
migration = cls()
migration.set_connection(db)
migration.up()
__all__ = list(__get_defined_modules()) + ['run_migrations']
另一种方法(我并不真正推荐)是使用这种方式的东西(我没有对此进行测试):
import inspect, importlib def try_xx()
try:
some_xx()
except NameError as e:
func_name = e.split("'")[1]
parts = func_name.split("_")
for _, f in inspect.getmembers(importlib.import_module("/module/path/{}.py".format(parts[1])), inspect.isfunction):
if f.__name__ == func_name:
f()
但是要回答你的问题......不,python没有内置的自动加载机制,因为大多数时候你不需要它。你可以在这里阅读一个很好的说明:Python 模块自动加载器?(关于 php 也有自动加载,但你会明白的)
推荐阅读
- javascript - Fabric JS + Gif图像动画不起作用
- ember.js - 在 ember 中访问控制器功能中的控制器属性
- git - 如何从 git remote 永久撤消最近的提交,但将其保存在我的本地?
- c# - 如何让 QnA maker 和 Luis BOT 的集成能够准确工作?
- r - 语言 R:变量在“for()”循环内不会改变?
- php - 如何从当前父类别中获取 Woocommerce 所有子类别
- reactjs - 当代码在服务器上时,从客户端或服务器端完成 React JS API 调用。?
- assembly - 试图将参数传递给过程但引发异常?
- node.js - 具有存储库的 Amazon AWS Lambda 函数......?
- php - 根据 WooCommerce 中的购物车项目总数隐藏所有运输方式