如何解决python类中有多个构造函数
我来自Java编程语言,我知道在那里可以有多个构造函数。
我现在的问题是:在Python中也可以吗?
我的问题:
我有一个课程历史记录,其中有我的命令帮助功能(由click
实现)。这些命令不在历史记录类中。现在我的命令有时只有一个input_dir
和一个output_file
,而没有temp_file
。或者只是input_dir
和output_file
。
我如何仍然使用具有3个或2个输入参数的相同构造函数?
class History():
def __init__(self,input_dir,output_file,temp_file):
self._input_dir = input_dir
self._output_file = output_file
self.temp_file = temp_file
def identify_ID(self):
'''Identifies the ID'''
@click.command(context_settings=CLICK_CONTEXT_SETTINGS,help='Creates history ',)
@click.option(
'-i','--input-directory',required=True,type=click.Path(exists=True,file_okay=False),help='input directory',)
@click.option(
'-o','--output-file',help='File of history',)
def create_user_history(input_directory,output_file):
history = History(input_directory,output_file) #here without temp-file
history.identify_ID()
#------------------------------------------
@click.command(context_settings=CLICK_CONTEXT_SETTINGS,help='Specify history ',)
@click.option(
'-t','--temp-file',help='temp-file of history',def specify_user_history(input_directory,temp_file):
history = History(input_directory,temp_file) #here without output-file
# another function,doesn't matter
解决方法
在python中没有方法重载这样的东西。因此,不可能有您想要的多个构造函数。但是,您可以将参数设为可选。
class History():
def __init__(self,input_dir=None,output_file=None,temp_file=None):
self._input_dir = input_dir
self._output_file = output_file
self.temp_file = temp_file
def identify_ID(self):
'''Identifies the ID'''
这将使您的论点组合生效。这样,您调用的方法就可以理解实例变量了。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。