如何从内部引用类(如递归函数) [英] How to refer to the class from within it (like a recursive function)

查看:48
本文介绍了如何从内部引用类(如递归函数)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于递归函数,我们可以做:

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 thing?

class A:
  # do something
  some_func(A)
  # ...

推荐答案

如果我正确理解了您的问题,则可以通过将类型注释放在引号中来引用A类中的A类.这称为前向参考.

If I understand your question correctly, you should be able to reference class A within class A by putting the type annotation in quotes. This is called forward reference.

class A:
  # do something
  def some_func(self, a: 'A')
  # ...

请参阅下面的参考文件

  1. https://github.com/python/mypy/issues/3661
  2. https://www.youtube.com/watch?v=AJsrxBkV3kc

这篇关于如何从内部引用类(如递归函数)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆