如何初始化辅助方法?

时间:2012-12-10 04:46:09

标签: python

如果我有两个文件helper.app和main.app,我希望能够完成这样的事情。

helper.py

def configurestuff(dblocationstring):
  # Stuff that sets name and location
  generic_connection_variable = connectto(dblocationstring)

def dostuff():
  # does stuff with the generic_connection_variable

在我的main.py中,我希望能够做类似

的事情
import helper
helper.configure("customlocationofdb")
helper.dostuff()
#or even
helper.generic_connection_variable.someApplicableMethod()

我的目标是,我可以使用一个main.app,它能够使用“帮助器”传递变量来设置连接,并在导入帮助程序后在main.app中重用该变量。组织我的代码来实现这一目标的最佳方法是什么? (我不知道如何在我的main.py中访问generic_connection_variable,因为它在函数中,或者最好的方法是这样做)

3 个答案:

答案 0 :(得分:1)

将其作为一个类实现可以提供更大的灵活性:

class Config(object):
    DB_STRING = 'some default value'
    ANOTHER_SETTING = 'another default'
    DEBUG = True

    def dostuff(self):
      print 'I did stuff to ',self.DEBUG

class ProductionConfig(Config):
    DEBUG = False # only turn of debugging

class DevelopmentConfig(Config):
    DB_STRING = 'localhost'

    def dostuff(self):
       print 'Warning! Development system ',self.DEBUG

将其存储在任何文件中,例如settings.py。在您的代码中:

from settings import Config as settings
# or from settings import ProductionConfig as settings

print settings.DEBUG # for example

答案 1 :(得分:1)

您可以将generic_connection_variable定义为模块级变量。

所以在helper.py中你必须

generic_connection_variable = None  # or whatever default you want.


def configurestuff(dblocationstring):
    global generic_connection_variable
    # Stuff that sets name and location
    generic_connection_variable = connectto(dblocationstring)

def dostuff():
    global generic_connection_variable
    # does stuff with the generic_connection_variable

答案 2 :(得分:0)

告诉你的问题有点难,但是你试过让generic_connection_variable成为helper的实例变量吗? (使用self关键字)

# helper.py:

def configurestuff(dblocationstring):
  # Stuff that sets name and location
  self.generic_connection_variable = connectto(dblocationstring)

既然generic_connection_variable属于helper的实例,而不是configurestuff的本地范围,您可以在main中使用它,如下所示:< / p>

import helper
helper.configure("customlocationofdb")
helper.generic_connection_variable.someApplicableMethod()

但您可能需要为generic_connection_variable定义一个类,因此它有一个名为someApplicableMethod()的方法。