[英]How to access class method and class variable from a class to another class's instance method in Python?
[英]How to change a variable value in a python parent class from sub class method just for class instance
好的,我什至不能完全確定我的標題是否完全准確,因為我當時完全不了解類繼承和實例,但是了解它是我需要或應該掌握的東西。
背景:嘗試為我的銀行創建一個自定義導入程序,以與流行的Beancount / fava雙重輸入分類帳會計系統一起使用。 我最初向fava報告是一個錯誤,但是后來意識到它不是錯誤,更多的是我缺乏對Python類的一般理解,因此認為在此處發布會更好。
所以...我創建了以下導入腳本文件,據我了解是beancount csv.Importer的子類( https://github.com/beancount/beancount/blob/master/beancount/ingest/importers/csv。 py )是beancount Importer的子類( https://github.com/beancount/beancount/blob/master/beancount/ingest/importer.py )
在我的導入器中,我使用了兩種csv.Importer方法,即name()和file_account()。 我的目標是基於文件名和字典查找來派生與輸入文件關聯的源帳戶。 我不希望在子類中重寫extract()方法,但是在csv.Importer extract()方法中引用了self.account,它代表用於提取的交易的源帳戶。 當前,如果我將腳本輸入名為“ SIMPLII_9999_2018-01-01.csv”的文件,則該腳本將被正確地導出為“ Assets:Simplii:Chequing-9999”。 但是,如果我沒有實際將事務導入到fava中,而是嘗試再次從同一文件中提取事務,則派生帳戶將變為“ Assets:Simplii:Chequing-9999 :Chequing-9999 ”。
我想做的是從輸入文件中獲取源帳戶,並將此信息作為我的類實例(我認為)的父類(csv.Importer)中的self.account變量傳遞。 我在課堂上做錯了什么,導致派生的源帳戶被結轉到下一個實例?
#!/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變量並返回結果。 似乎更多的工作不是適當的方法,但至少是在這里,以防它幫助其他人。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.