如何访问Python中函数内部声明的变量

0 投票
3 回答
5134 浏览
提问于 2025-04-17 16:14

我有一段代码,它读取配置文件,并把结果存储在一些变量里,像是一个列表。

import ConfigParser

def read_config_file():
    config = ConfigParser.ConfigParser()
    cnf_path = 'config_files/php.sr'
    config.read(cnf_path)
    if config.has_section('basic'):
        if config.has_option('basic', 'basic'):
            php_bsc_mdls = config.get('basic', 'basic').split(',')
    if config.has_section('advance'):
        if config.has_option('advance','advance'):
            php_adv_mdls = config.get('advance', 'advance').split(',')

现在我想从这个函数中获取结果变量 php_bsc_mdlsphp_adv_mdls,类似于 read_config_file.php_bsc_mdlsread_config_file.php_adv_mdls 这样的方式。

那么,能不能从这个 Python 函数中访问或获取这些变量呢?

3 个回答

0
def read_config_file():
  php_bsc_mdls, php_adv_mdls = None, None # Init to None.
  ...
  return php_bsc_mdls, php_adv_mdls # Return at end.

# Get results
basic, advanced = read_config_file()

另外,你可以为这个创建一个类。

class Config:
  php_adv_mdls = None
  php_bsc_mdls = None
  @staticmethod
  def read_config_file():
    if not Config.php_adv_mdls and not Config.php_bsc_mdls:
      # Load the data here.
      config = ConfigParser.ConfigParser()
      ...
      Config.php_adv_mdls = config.get...
      Config.php_bsc_mdls = config.get...

使用类里的变量和静态方法来一次性加载你的配置文件。

Config.php_adv_mdls # None
Config.read_config_file() # Loads the data from config.
Config.read_config_file() # Will only attempt another load if either 
                          # class variable in not valid.
Config.php_bsc_mdls       # If successful, will be initialize with data.
0

正如之前所说,使用返回值来处理这个问题是合理的。

但是……

在Python中,函数也是一种对象,所以你可以这样做:

def a():
    a.x = 10

a()
print a.x    # >> 10

最后,虽然这不是一个好代码的例子,但在这种情况下可以这样使用。

1

你只需要把它们返回就行了。当函数结束时,它们就不再存在了。

def read_config_file():
    config = ConfigParser.ConfigParser()
    cnf_path = 'config_files/php.sr'
    config.read(cnf_path)
    if config.has_section('basic'):
        if config.has_option('basic', 'basic'):
            php_bsc_mdls = config.get('basic', 'basic').split(',')
    if config.has_section('advance'):
        if config.has_option('advance','advance'):
            php_adv_mdls = config.get('advance', 'advance').split(',')

    if php_bsc_mdls and php_adv_bls:
        return php_bsc_mdls,php_adv_mdls
    elif php_bsc_mdls:
        return php_bsc_mdls, None

另一种方法是使用一个类,把它们保存到类的变量里。然后你可以从这个类中获取这些值,而不是从函数中获取。

或者像这样:

def read_config_file():
    php_bsc_mdls = None
    php_adv_mdls = None
    config = ConfigParser.ConfigParser()
    cnf_path = 'config_files/php.sr'
    config.read(cnf_path)
    if config.has_section('basic'):
        if config.has_option('basic', 'basic'):
            php_bsc_mdls = config.get('basic', 'basic').split(',')
    if config.has_section('advance'):
        if config.has_option('advance','advance'):
            php_adv_mdls = config.get('advance', 'advance').split(',')

    return php_bsc_mdls, php_adv_mdls

无论哪种情况,你都需要在调用函数的地方检查返回值。看看这些值是否存在。

撰写回答