如何在python中传递给类类型的类方法参数? [英] How to pass to class method argument of class type in python?

查看:56
本文介绍了如何在python中传递给类类型的类方法参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类,想定义一个方法,该方法接受类似这样的类类型的参数:

I have a class and would like to define a method that accepts an argument of the same class type like this:

class MyClass:

  def my_method(self, param: MyClass):
    pass

但是我有一个错误未解析的引用'MyClass'

如何解决此问题?

推荐答案

来自

当类型提示中包含尚未定义的名称时,该定义可以表示为字符串文字,稍后再解决.

When a type hint contains names that have not been defined yet, that definition may be expressed as a string literal, to be resolved later.

因此您可以将您的班级名称放在引号中

So you can put your class name inside the quotes:

class MyClass:
  def my_method(self, param: 'MyClass'):
    pass

这篇关于如何在python中传递给类类型的类方法参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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