内联修改后,将一个文件中的变量作为类变量传递到另一个文件中 [英] Passing a variable from one file into another as a class variable after inline modification
问题描述
我想知道是否有可能从一个python文件中获取一个变量(基本上是一个列表)到主程序文件中,然后将其传递到主程序文件中的类对象中,而无需先在程序文件.我将在下面说明情况.文件words.py有一个名为wordlist的列表.我将此单词表导入到主程序文件main.py中,例如:
I was wondering whether its possible to get a variable (basically a list) from one python file into the main program file and then pass it into a class object in the main program file without first defining the variable (WORDS below) in the program file. I will explain the situation below. File words.py has a list named wordlist. I import this wordlist into the main program file main.py like:
# words.py file
wordlist = ['an',''..] # some list of words
# main.py
from words import wordlist
WORDS = wordlist.copy()
WORDS.remove('an')
mc = models_class(word_list = WORDS)
正如我尝试过的那样,如果我首先定义一个局部变量WORDS,但是如果我直接将wordlist传递到类对象中并在其中应用remove,则它可以工作,如下所示.
As i have tried the above works if i first define a local variable WORDS but can it work if i directly pass the wordlist into the class object and apply remove there, like below.
mc = models_class(word_list = wordlist.remove('an'))
推荐答案
您不能喜欢 word_list = wordlist.remove('an')
,因为 remove
是就地操作,仅更新原始列表并返回None.
You can not do like word_list = wordlist.remove('an')
because remove
is an in-place operation which just update the original list and return None.
请参见更多列表中的Python >
您可能已经注意到,仅修改列表的插入,删除或排序之类的方法没有打印返回值–
它们返回默认值None
.1这是Python中所有可变数据结构的设计原则.
You might have noticed that methods like insert, remove or sort that only modify the list have no return value printed –
they return the default None
. 1 This is a design principle for all mutable data structures in Python.
这篇关于内联修改后,将一个文件中的变量作为类变量传递到另一个文件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!