python: how to refer to the class from within it ( like the recursive function)

后端 未结 13 1800
旧时难觅i
旧时难觅i 2020-12-10 10:10

For a recursive function we can do:

def f(i):
  if i<0: return
  print i
  f(i-1)

f(10)

However is there a way to do the following thin

13条回答
  •  情歌与酒
    2020-12-10 10:44

    Do remember that in Python, type hinting is just for auto-code completion therefore it helps IDE to infer types and warn user before runtime. In runtime, type hints almost never used(except in some cases) so you can do something like this:

    from typing import Any, Optional, NewType
    
    LinkListType = NewType("LinkList", object)
    
    
    class LinkList:
        value: Any
        _next: LinkListType
    
        def set_next(self, ll: LinkListType):
            self._next = ll
    
    
    if __name__ == '__main__':
        r = LinkList()
        r.value = 1
        r.set_next(ll=LinkList())
        print(r.value)
    

    And as you can see IDE successfully infers it's type as LinkList:

    Note: Since the next can be None, hinting this in the type would be better, I just didn't want to confuse OP.

    class LinkList:
        value: Any
        next: Optional[LinkListType]
    
    

提交回复
热议问题