加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

Python重载__init__

发布时间:2020-12-20 12:09:44 所属栏目:Python 来源:网络整理
导读:如何在 Python中重载__init __()?我已经习惯了C/C++,编译器可以看到数据类型的差异,但由于Python中没有数据类型,当我将字符串作为参数时,如何确保调用第三个方法而不是第二个方法而不是一个int? class Handle: def __init__(self): self.pid = -1 def __in
如何在 Python中重载__init __()?我已经习惯了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

解决方法

在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,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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读