Python 重载 __init__

标签 python oop overriding

如何在 Python 中重载 __init__()?我习惯了 C/C++,编译器可以看到数据类型的差异,但是由于 Python 中没有数据类型,当我将字符串作为参数时,如何确保调用第三个方法而不是第二个方法而不是一个整数?

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

关于Python 重载 __init__,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34483719/

相关文章:

python - 如何使用 SQLAlchemy 检查 PostgreSQL 模式是否存在?

python - 在 python 中控制 SSL 握手的模块?

python - 如何用字典创建华夫饼图?

java - 如何在Java中将1个文件程序分解为多个类?

c++ - C++中的继承语法

javascript - 无法覆盖 JS 函数

c++ - 关于继承和覆盖的问题

python - 在 keras fit_generator() 中未调用 on_epoch_end()

java - 对具有必填字段和可选字段的对象进行最佳匹配搜索

css - 关闭 CSS 属性