Python-检查类是否存在 [英] Python - check for class existance

查看:43
本文介绍了Python-检查类是否存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以检查一个类是否已定义/存在?我在菜单上有不同的选项,其中一些需要继承的变量,因此,如果您在设置变量之前尝试选择该函数,则会崩溃.我的班级叫做Gen0,我通过简单地放入

Is there a way to check if a class has been defined/exists? I have different options on a menu, and some of them require inherited variables, so if you try to select that function before you have set the variables, it crashes. My class is called Gen0, and I started it by simply putting

class Gen0():

接着其余的代码来设置变量.对于上下文,我正在进行总体模型,因此需要在显示(选项2),使用(选项3)或导出(选项4)之前设置初始值(选项1).

Followed by the rest of the code to set the variables. For context, I am doing a population model, so the initial values need to be set (option 1) before displaying (option 2), using (option 3) or exporting (option 4) them.

推荐答案

您的情况尚不完全清楚,因此我将回答是否有办法检查是否定义/存在一个类?"

Your situation is not entirely clear, so I'm just going to answer the question "Is there a way to check if a class has been defined/exists?"

是的,有一些方法可以检查当前范围内是否已定义一个类.我会讲几个.

Yes, there are ways to check if a class has been defined in the current scope. I'll go through a few.

只需尝试使用它!

try:
    var = MyClass()
except NameError:
    # name 'MyClass' is not defined
    ...

这可能是最Pythonic的方法(除了确保已导入/定义了类之外).

This is probably the most Pythonic method (aside from just being sure you have the class imported/defined).

当前范围内的所有内容均由 dir()给出.当然,这将无法处理导入的内容!(除非它们是直接导入的.)

Everything in the current scope is given by dir(). Of course, this won't handle things that are imported! (Unless they are imported directly.)

if not 'MyClass' in dir():
    # your class is not defined in the current scope
    ...

3.检查模块的内容

也许您想查看该类是否在特定模块 my_module 中定义.所以:

import my_module
import inspect

if not 'MyClass' in inspect.getmembers(my_module):
    # 'MyClass' does not exist in 'my_module'
    ...


现在,值得指出的是,如果您随时在生产代码中使用这些东西,那么您可能编写的代码不佳.您应该始终知道在任何给定时刻范围内的类.毕竟,这就是我们拥有导入语句和定义的原因.我建议您使用更多示例代码来整理问题,以获得更好的答复.


Now, it's worth pointing out that if at any point you are using these sorts of things in production code, you're probably writing your code poorly. You should always know which classes are in scope at any given point. After all, that's why we have import statements and definitions. I'd recommend you clean up your question with more example code to receive better responses.

这篇关于Python-检查类是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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