首页 > 解决方案 > 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中有这样的实现吗?

标签: python-3.x

解决方案


好吧,这实际上取决于您想要实现的目标。例如,对于自动加载丢失的包,您可以执行类似于此页面的操作

   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 也有自动加载,但你会明白的)


推荐阅读