如何从仅用于类实例的子类方法更改 python 父类中的变量值



好吧,我什至不完全确定我的标题是否完全准确,因为我当时完全不了解类继承和实例,但理解这是我需要或应该掌握的东西前进。

背景:尝试为我的银行创建自定义导入器,以与流行的Beancount/fava复式记账会计系统一起使用。 我最初向 fava 报告为一个错误,但后来意识到它不是一个错误,更多的是我对 Python 类缺乏一般理解,所以认为最好在这里发布。

所以。。。我创建了以下导入脚本文件,据我了解,它是beancount csv的子类。进口商 (https://github.com/beancount/beancount/blob/master/beancount/ingest/importers/csv.py( 是豆计数进口商 (https://github.com/beancount/beancount/blob/master/beancount/ingest/importer.py( 的一个子类

在我的进口商中,我覆盖了 2 种 csv 方法。导入器、名称 (( 和 file_account((。 我的目标是根据文件名和字典查找派生与输入文件关联的源帐户。 extract(( 方法我不希望在我的子类中覆盖,但是在 csv 中。导入程序 extract(( 方法引用了 self.account,它表示用于提取事务的源帐户。 目前,我的脚本方式是,如果我给它提供一个名为"SIMPLII_9999_2018-01-01.csv"的文件,该帐户将正确派生为"资产:Simplii:Checkquing-9999"。 但是,如果我没有在 fava 中实际导入交易,而是尝试从同一文件中再次提取交易,则派生帐户将变为"资产:Simplii:支票-9999:支票-9999"。

我正在尝试做的是从输入文件中派生源帐户,并将此信息作为父类 (csv.导入器(为我的类实例(我认为(。 我在类中做错了什么,导致派生源帐户被转移到下一个实例?

#!/usr/bin/env python3
from beancount.ingest import extract
from beancount.ingest.importers import csv
from beancount.ingest import cache
from beancount.ingest import regression
import re
from os import path
from smart_importer.predict_postings import PredictPostings
class SimpliiImporter(csv.Importer):
'''
Importer for the Simplii bank.
Note: This undecorated class can be regression-tested with
beancount.ingest.regression.compare_sample_files
'''
config = {csv.Col.DATE: 'Date',
csv.Col.PAYEE: 'Transaction Details',
csv.Col.AMOUNT_DEBIT: 'Funds Out',
csv.Col.AMOUNT_CREDIT: 'Funds In'}
account_map = {'9999':'Chequing-9999'}
def __init__(self, *, account, account_map=account_map):
self.account_map = account_map
self.account = 'Assets:Simplii'
super().__init__(
self.config,
self.account,
'CAD',
['Filename: .*SIMPLII_d{4}_.*.csv',
'Contents:n.*Date, Transaction Details, Funds Out, Funds In'],
institution='Simplii'
)
def name(self):
cls = self.__class__
return '{}.{}'.format(cls.__module__, cls.__name__)
def file_account(self, file):
__account = None
if file:
m = re.match(r'.+SIMPLII_(d{4})_.*', file.name)[1]
if m:
sub_account = self.account_map.get(m)
if sub_account:
__account = self.account + ':' + sub_account
return __account
def extract(self, file):
self.account = self.file_account(file)
return super().extract(file)

@PredictPostings(training_data='/beancount/personal.beancount')
class SmartSimpliiImporter(SimpliiImporter):
'''
A smart version of the Simplii importer.
'''
pass

所以我设法让它工作,但我认为这不是正确的方法......

我像这样更改了提取函数

def extract(self, file):
self.account = self.file_account(file)
postings = super().extract(file)
self.account = 'Assets:Simplii'
return postings

基本上我将 self.account 设置为我需要的值,调用父类提取函数将结果保存到变量,重置 self.account 变量并返回结果。 似乎比正确的方法更像是一种解决方法,但至少它在这里以防万一它可以帮助其他人......

最新更新