你可以参考
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。