如何在 class 中从文件中读取参数?

How to read parameters from a file when inside a class?

假设我有一个 Python class 这样的:

class Person:
  def __init__(self): 
    self.alive = True
    self.name = 'Alice'
    self.age = 20

如何从这个 class 中的外部文件读取参数?我想它可能类似于以下伪代码:

class Person:
  def __init__(self, filename): 
    self.alive = True                    # same for all persons
    with open(filename, 'r') as f: 
      self.name = f.somehow_read_name    # different for all persons
      self.age = f.somehow_read_age

我可以做到:

alice = Person('alice.txt')
bob = Person('bob.txt')

我希望外部 'alice.txt' 文件是人类可读的,所以可能是这样的:

name = 'Alice' # Name of the person
age  = 20      # Age of the person
### OR ###
{
name : 'Alice', # Name of the person
age  : 20       # Age of the person
}
### OR ###
self.name = 'Alice'
self.age  = 20

其中参数的顺序重要。 到目前为止,我一直在这样做:

with open(filename, "r") as f:
  parameters = f.readlines()
  self.name = parameters[8]

当 'alice.txt' 文件内部发生变化时,维护起来显然非常乏味。

那么你有两种方法:

首先,使用 pickle 将您的 python 数据存储在其中并检索。使用此 link 了解更多信息 https://docs.python.org/3/library/pickle.html .

其次,您可以使用特定的文件格式来存储和检索数据,例如 CSV、JSON、excel 等...

我想我找到了一个不错的方法。我尝试在 class 中执行 from alice import *,但没有成功(因为 *)。但是,只要外部文件被称为 ***.py 并且我将其导入到 class 中,如下所示:

import alice # if the file is 'alice.py'

然后我可以通过 alice.name 等访问该文件中定义的变量并执行以下操作:

import alice
self.name = alice.name
self.age  = alce.age

此解决方案为人类可读文件创建了一个解析器

代码

class Person:
    def __init__(self, filenm): 
        self.alive = True
        # Get attributes as dictionary
        d = get_attributes_from_file(filenm)

        # Set attributes from dictionary
        for k, v in d.items():
            setattr(self, k, v)

    def __str__(self):
        # Atributes of object as string (to allow printing of object)
        return str(self.__dict__)
        
def get_attributes_from_file(filenm):
    '''
        Parses attribute file
            returns dictionary of attributes
    '''
    
    
    with open(filenm, 'r') as f:
        # Read file contents
        s = f.read()

        # remove comments
        s = ' '.join(x.split('#')[0] for x in s.splitlines())   
        
        # Convert to dictionary
        # uses comma as delimiter
        d = dict([
                    (term.split(':')[0].strip(), term.split(':')[1].strip("' "))
                    for term in s.strip("{}").split(',')
                ])
    
    return d

用法

tom = Person('tom.txt')
dick = Person('dick.txt')
mary = Person('mary.txt')
phyllis = Person('phyllis.txt')

print(tom)  # output: {'alive': True, 'name': 'tom', 'age': '20'}
print(dick) # outptu: {'alive': True, 'name': 'dick', 'age': '25'}
print(mary) # {'alive': True, 'name': 'mary', 'age': '35', 'gender': 'female'}
print(phyllis) # Output: {'alive': True, 'name': 'phyllis', 'age': '35', 'gender': 'female', 'sibling': 'tom'}

文件

tom.txt:

name: tom,            # comment such as this are ignored
age: 20               # age

dick.txt

name: dick,
age: 25

mary.txt

name: 'mary',       # attributes can be with or without quotes
age: 35,
gender: female     # can have extra attributes

phyllis.txt(仅显示注释行和空行)

name: 'phyllis',
age: 35,   # age in years

gender: female,
#relatives 
sibling: 'tom'