給定一個將 .csv 檔案匯出到資料庫的類:
import luigi
import csv
class CsvToDatabase(luigi.Task):
# (...)
def run(self):
## (...)
with open(self.input().some_attribute, 'r', encoding='utf-8') as some_dataframe:
y = csv.reader(some_dataframe, delimiter=';')
### (...) <several lines of code>
# (...)
我在嘗試匯出具有 ISO-8859-1 編碼的檔案時遇到問題。
當我encoding從 thenopen()函式中排除引數時,一切正常,但我無法對類定義進行永久更改(公司的其他部門使用它)。于是想到了用多型來解決的可能性,比如:
from script_of_interest import CsvToDatabase
class LatinCsvToDatabase(CsvToDatabase):
# code that uses everything in `run()` except the `some_dataframe` definition in the with statement
這種可能性真的存在嗎?我怎么能在不重復陳述句中的“幾行代碼”的情況下處理它?
uj5u.com熱心網友回復:
謝謝@martineau 和@buran 的評論。基于它們,我將要求在不影響其他部門作業的情況下更改基類定義。它看起來像這樣:
import luigi
import csv
class CsvToDatabase(luigi.Task):
# (...)
encoding_param = luigi.Parameter(default='utf-8') # as a class attribute
# (...)
def run(self):
## (...)
with open(self.input().some_attribute, 'r', encoding=self.encoding_param) as some_dataframe:
y = csv.reader(some_dataframe, delimiter=';')
### (...) <several lines of code>
# (...)
最后,在我的腳本中,類似于:
from script_of_interest import CsvToDatabase
class LatinCsvToDatabase(CsvToDatabase):
pass
LatinCsvToDatabase.encoding_param = None
uj5u.com熱心網友回復:
您可以考慮修改原始類以添加新方法作為替代方法get_cvs_encoding,該方法使用該run方法:
class CsvToDatabase(luigi.Task):
...
def get_cvs_encoding(self):
# default:
return 'utf-8'
def run(self):
## (...)
with open(self.input().some_attribute, 'r', encoding=self.get_cvs_encoding()) as some_dataframe:
y = csv.reader(some_dataframe, delimiter=';')
...
}
然后將其子類化如下:
class MyCsvToDatabase(CsvToDatabase):
def get_cvs_encoding(self):
return 'ISO-8859-1' # or None
并使用子類的實體。我只是認為這更簡潔,您可以同時“運行”多個子類實體。
uj5u.com熱心網友回復:
在您發布答案后,我認為最好發布一些替代方案。所以,這是你當前的課程,最小的例子
class A:
def run(self):
# some code
with open('some_file.csv' , encoding='utf-8'):
pass
# more code
我的想法,在意見建議-改變A類,并添加引數encoding到A.run()默認值utf-8。這樣更改就不會影響其他人(他們使用 A 類的現有代碼)。
class A:
def run(self, encoding='utf-8'):
# some code
with open('some_file.csv' , encoding=encoding):
pass
# more code
然后在你的代碼中
a=A() # create instance of A
a.run(encoding=None)
現在,您添加 class 屬性的想法。這就是你決定改變A類的方式:
class A:
encoding='utf-8'
def run(self):
# some code
with open('some_file.csv', encoding=self.encoding):
pass
# more code
我認為你不需要子類化。有了這個新的 A 類,你可以做到
a=A() # create instance of the new class A
a.encoding=None # note, in run() you use self.encoding and this will work. still A.encoding is utf-8 and others will not be affected.
如果你堅持繼承新的 A 類
class B(A):
encoding=None
然后在您的代碼中,您可以使用 B 類的實體。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/314645.html
上一篇:選擇具有相同名稱的第二部分的第二個元素,CSS-NTH
下一篇:PythonOOB:不理解子類
