我正在尝试理解 Python 中的继承。我有 4 种不同类型的日志要处理:cpu、ram、网络和磁盘使用情况
我决定用类来实现它,因为除了日志文件读取和数据的数据类型之外,它们在形式上是相同的。我有以下代码(日志对象是自定义日志记录类的日志记录对象实例)
class LogFile():
def __init__(self,log_file):
self._log_file=log_file
self.validate_log()
def validate_log(self):
try:
with open(self._log_file) as dummy_log_file:
pass
except IOError as e:
log.log_error(str(e[0])+' '+e[1]+' for log file '+self._log_file)
class Data(LogFile):
def __init__(self,log_file):
LogFile.__init__(self, log_file)
self._data=''
def get_data(self):
return self._data
def set_data(self,data):
self._data=data
def validate_data(self):
if self._data == '':
log.log_debug("Empty data list")
class DataCPU(Data):
def read_log(self):
self.validate_log()
reading and writing to LIST stuff
return LIST
class DataRAM(Data):
def read_log(self):
self.validate_log()
reading and writing to LIST stuff
return LIST
class DataNET(Data):
现在我希望我的 DataNET
类成为 Data
类的一个对象,具有更多属性,特别是每个接口(interface)的字典。我如何重写 __init__()
方法使其与 Data.__init__()
相同但添加 self.dict={}
而不复制数据生成器?也就是说,没有明确指定 DataNet
对象确实具有 ._data
属性,但继承自 Data
。
最佳答案
只需从 DataNET.__init__()
调用 Data.__init__()
方法,然后设置 self._data = {}
:
class DataNET(Data):
def __init__(self, logfile):
Data.__init__(self, logfile)
self._data = {}
现在无论 Data.__init__()
对 self
做什么,都会先发生,让您的 DataNET
初始化程序添加新属性或覆盖由父初始化器。
在 Python 3 中,类已经是新样式了,但如果这是 Python 2,我会将 object
作为基类添加到 LogFile()
中以使其成为也是新式的:
class LogFile(object):
之后您可以使用 super()
自动查找要调用的父 __init__
方法;这样做的好处是,在更复杂的协作继承方案中,正确的方法会以正确的顺序调用:
class Data(LogFile):
def __init__(self,log_file):
super(Data, self).__init__(log_file)
self._data = ''
class DataNET(Data):
def __init__(self, logfile):
super(DataNET, self).__init__(logfile)
self._data = {}
super()
为您提供绑定(bind)方法,因此您无需将 self
作为参数传入 __init__
案件。在 Python 3 中,您可以完全省略 super()
的参数:
class Data(LogFile):
def __init__(self,log_file):
super().__init__(log_file)
self._data = ''
class DataNET(Data):
def __init__(self, logfile):
super().__init__(logfile)
self._data = {}
关于python - Python中的继承,init方法重写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23287392/