假設我有一個這樣的 Python 類:
class Person:
def __init__(self):
self.alive = True
self.name = 'Alice'
self.age = 20
如何從此類中的外部檔案讀取引數?我想它可能類似于以下偽代碼:
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”檔案中的某些內容發生變化時,這顯然非常繁瑣。
uj5u.com熱心網友回復:
此解決方案為人類可讀的檔案創建了一個決議器
代碼
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'}
檔案
湯姆.txt:
name: tom, # comment such as this are ignored
age: 20 # age
迪克.txt
name: dick,
age: 25
瑪麗.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'
uj5u.com熱心網友回復:
那么你有兩種方法:
首先,使用pickle 將您的python 資料存盤在其中并檢索。使用此鏈接獲取更多資訊https://docs.python.org/3/library/pickle.html。
其次,您可以使用特定的檔案格式來存盤和檢索您的資料,例如 CSV、JSON、excel 等...。
uj5u.com熱心網友回復:
我想我找到了一個很好的方法。我試圖from alice import *在課堂上做,但沒有奏效(因為*)。但是,只要呼叫外部檔案***.py并將其匯入到類中,如下所示:
import alice # if the file is 'alice.py'
然后我可以通過alice.name等訪問該檔案中定義的變數并執行以下操作:
import alice
self.name = alice.name
self.age = alce.age
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/396928.html
上一篇:創建超類和子類Java問題
