1

helper.app と main.app の 2 つのファイルがある場合、このようなことを実現できるようにしたいと考えています。

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にアクセスする方法、またはこれを行う最良の方法がわかりません)

4

3 に答える 3

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
于 2012-12-10T06:51:17.553 に答える
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
于 2012-12-10T04:57:25.130 に答える
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インスタンスに属するようになり、次のように使用できるようになります。helperconfigurestuffmain

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

しかし、おそらくクラスを定義しgeneric_connection_variableて、 というメソッドを持たせる必要がありますsomeApplicableMethod()

于 2012-12-10T04:50:41.493 に答える