簡體   English   中英

將變量(帶求值)導入類名稱空間(即self.varName)

[英]Import variables (with evaluation) to class namespace (i.e. self.varName)

我有一個python文件input.py 有注釋以及空格和制表符的組合,僅用於很好的衡量。

# comment1 or header
name    =   "project1"
length  = 100.0 # comment2
width   = 20.0
area = length * width
circumference = 2*length + 2*width
        # orphaned comment

我想將變量(其中一些是從其他變量求值的)讀取到我的類結構中,以便可以像self.area一樣訪問self.area

import importlib
class Project:     
    def __init__(self, inFile):
        self.inFile = inFile
        ## from self.inFile import * # definitely not gonna work! 
        importlib.import_module(inFile) # doesn't work either! 
p1 = Project(r"/home/feedme/input.py")
print p1.area

所需的示例輸出:

2000.0 

除了從from something import *通常不是一個好主意的事實之外,我還能用什么將變量以這種方式帶入類中?

編輯:刪除了關於導入名稱為字符串的模塊的其他問題,因為我已經找到答案了; importlib

我建議使用runpy模塊。 下面的代碼將在傳遞給類初始化程序的路徑上執行python腳本,並將所有非dunder變量加載到實例字典中:

import runpy

class Project(object):

    def __init__(self, path):
        module = runpy.run_path(path)
        for k, v in module.items():
            if not k.startswith('__'):
                self.__dict__[k] = v

例如:

>>> project = Project('conf.py')
>>> project.area
2000.0

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM