私は自分のプログラムでさまざまな機能を分けて、物事を整理しようとしています。そして、あるモジュールで作成された変数を別のモジュールで使用しようとしています。私はglobal list_of_names
を使ってみましたが、うまくいきませんでした。とにかくそうしないことをお勧めします。モジュール間で変数を使用する最も良い方法は? (Python3)
以下は私のコードのサンプルです。私の意見では、list_of_names
を関数の引数として渡すのは意味がありません。なぜなら、渡すべき実際の引数を除いて、これを行う必要がある他の複数の変数があるからです。
残念ながら、私がread_json
をengine.pyに移動しても、私は同じように問題を起こしていました。また、list_of_names
も参照する必要があります。
# main.py:
import json
from engine import create_person
def read_json():
with open('names.json', 'r') as file
data = json.load(file)
return data
list_of_names = read_json()
person1 = create_person()
# engine.py:
from random import choice
def create_person():
name = choice(list_of_names)
new_person = {
'name': name,
# other keys/values created in similar fashion
}
return new_person
EDIT1: ここに私の新しいコードです。私にとって、これはパラメータリストを作成して関数内で分解するのは効率的ではないようです。 (私はこの例では変数名を再利用していることを知っています)次に、これらのパラメータのいくつかを他の関数に渡す必要があります。一般的に
# main.py:
import json
from engine import create_person
def read_json():
with open('names.json', 'r') as file
data = json.load(file)
return data
player_id_index = 0
list_of_names = read_json()
person_parameters = [
list_of_names,
dict_of_locations,
player_id_index,
dict_of_occupations,
.
.
.
]
person1, player_id_index = create_person()
# engine.py:
from random import choice
def create_person(person_params):
list_of_names = person_params[0]
dict_of_locations = person_params[1]
player_id_index = person_params[2]
dict_of_occupations = person_params[3]
.
.
.
attr = person_params[n]
name = choice(list_of_names)
location = get_location(dict_of_locations) # a function elsewhere in engine.py
p_id = player_id_index
occupation = get_occupation(dict_of_occupations) # a function elsewhere in engine.py
new_person = {
'name': name,
'hometown': location,
'player id': p_id,
'occupation': occupation,
.
.
.
}
player_id_index += 1
return new_person, player_id_index
複数のモジュール間で同じ変数を使用しないでください。ほとんどの場合、同じ変数を複数の関数に渡って使用しないでください。関数の引数と戻り値は、ほとんどの場合、関数間でデータを渡す正しい方法です。 – user2357112
上記で要約すると、あなたのコードにはいくつかのOOP(Object Oriented Programming)構造がありますか?コードを読みやすく、メンテナンス性と再利用性が向上します。 – 0xDEFACED
@StevenRumbalski @ user2357112 'create_person(mylist)'のような意味ですか?私が述べたように、このように関数に多くの引数を渡さなければならないので、実用的ではありません。 – drewd423