Py学习  »  Python

Python是类在同一个类的定义中的实例

Jerry Halisberry • 3 年前 • 1057 次点击  

我想做点像

class my_class:
    def __add__(self, other: "my_class") -> "my_class":
        if isinstance(other, some_other_class):
            return other + self
        elif isinstance(other, my_class):
            return <special_adding_technique>
        else:
            raise NotImplementedError()

但我不能,因为我不能引用我的_类本身。我可以用try-except或check来打字 has_attr ,但这远不如简单地检查干净 isinstance .我能做些什么,既简单又不显得粗糙?

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/133576
 
1057 次点击  
文章 [ 1 ]  |  最新文章 3 年前
ShadowRanger
Reply   •   1 楼
ShadowRanger    3 年前

你可以参考 my_class 它的内部很好。你不能提及 我的班 当它被定义时(在任何方法之外,在类定义范围的顶层,或在函数的参数定义中),但是你可以在一个方法中引用它,直到你完成定义后才会被调用 我的班 .这里唯一的问题是基于字符串的注释有点难看,可以绕过自引用限制,这可以通过 __future__ 进口

from __future__ import annotations  # Supported as of 3.7, on by default beginning in 3.11

class my_class:
    def __add__(self, other: my_class) -> my_class:
        if isinstance(other, some_other_class):
            return other + self
        elif isinstance(other, my_class):
            return <special_adding_technique>
        return NotImplemented   # When you can't work with the other type, you're supposed
                                # to return the NotImplemented singleton, not raise
                                # NotImplementedError, where the latter is for completely
                                # unimplemented functionality, usually in an ABC

顺便说一句,Python类是 lowercase lowercase_with_underscores ; 类使用 CapWords ,所以这个类应该命名为 MyClass 遵守PEP8。