我如何__init__()
在Python中重载?我已经习惯了C/C++,其中编译器可以看到数据类型的差异,但由于Python中没有数据类型,当我将字符串作为参数时,如何确保调用第三个方法而不是第二个方法而不是一个int?
class Handle: def __init__(self): self.pid = -1 def __init__(self, pid): self.pid = pid def __init__(self, procname): print(procname) self.pid = -1 # find pid by name
Andrea Corbe.. 6
在C++中,您可以定义具有相同名称和不同签名的多个函数/方法.在Python中,每次定义一个与之前定义的函数同名的新函数时,都要替换它.
要实现您想要的,您必须使用可选参数和/或显式检查.
以下是一些可能的解决方案:
class Handle: def __init__(self, pid=-1): if isinstance(pid, str): self.procname = pid self.pid = -1 else: self.procname = None self.pid = pid
class Handle: # Both pid and procname may be specified at the same time. def __init__(self, pid=-1, procname=None): self.procname = procname self.pid = pid
class Handle: # Either pid or procname, not both, may be specified. def __init__(self, pid=-1, procname=None): if pid >= 0 and procname is not None: raise ValueError('you can specify either pid or procname, not both') self.procname = procname self.pid = pid
class Handle: def __init__(self, pid=-1): self.pid = pid # A separate constructor, with a different name, # because "explicit is better than implicit" and # "sparse is better than dense" (cit. The Zen of # Python). # In my opinion, this is the most Pythonic solution. @classmethod def from_process_name(cls, procname): pid = get_pid(procname) return cls(pid)
顺便说一句,我不建议使用-1
"未指定".我宁愿用None
.
在C++中,您可以定义具有相同名称和不同签名的多个函数/方法.在Python中,每次定义一个与之前定义的函数同名的新函数时,都要替换它.
要实现您想要的,您必须使用可选参数和/或显式检查.
以下是一些可能的解决方案:
class Handle: def __init__(self, pid=-1): if isinstance(pid, str): self.procname = pid self.pid = -1 else: self.procname = None self.pid = pid
class Handle: # Both pid and procname may be specified at the same time. def __init__(self, pid=-1, procname=None): self.procname = procname self.pid = pid
class Handle: # Either pid or procname, not both, may be specified. def __init__(self, pid=-1, procname=None): if pid >= 0 and procname is not None: raise ValueError('you can specify either pid or procname, not both') self.procname = procname self.pid = pid
class Handle: def __init__(self, pid=-1): self.pid = pid # A separate constructor, with a different name, # because "explicit is better than implicit" and # "sparse is better than dense" (cit. The Zen of # Python). # In my opinion, this is the most Pythonic solution. @classmethod def from_process_name(cls, procname): pid = get_pid(procname) return cls(pid)
顺便说一句,我不建议使用-1
"未指定".我宁愿用None
.