gpt4 book ai didi

python - 识别变量是Python中的新型类?

转载 作者:太空狗 更新时间:2023-10-29 17:33:31 26 4
gpt4 key购买 nike

我正在使用 Python 2.x,我想知道是否有办法判断一个变量是否是一个新式类?我知道如果它是一个旧式类,我可以执行以下操作来找出答案。

import types

class oldclass:
pass

def test():
o = oldclass()
if type(o) is types.InstanceType:
print 'Is old-style'
else:
print 'Is NOT old-style'

但我还没有找到任何适用于新型类(class)的东西。我找到了 this question ,但建议的解决方案似乎没有按预期工作,因为简单的值被标识为类。

import inspect

def newclass(object):
pass

def test():
n = newclass()
if inspect.isclass(n):
print 'Is class'
else:
print 'Is NOT class'
if inspect.isclass(type(n)):
print 'Is class'
else:
print 'Is NOT class'
if inspect.isclass(type(1)):
print 'Is class'
else:
print 'Is NOT class'
if isinstance(n, object):
print 'Is class'
else:
print 'Is NOT class'
if isinstance(1, object):
print 'Is class'
else:
print 'Is NOT class'

那么有没有办法做这样的事情呢?还是 Python 中的一切都只是一个类,没有办法解决这个问题?

最佳答案

我认为您要问的是:“我可以测试一个类是否在 Python 代码中定义为新式类吗?”。 int 等技术上简单的类型新式类,但仍然可以将用 Python 编写的类与内置类型区分开来。

这里有一些有用的东西,尽管有点 hack:

def is_new_style(cls):
return hasattr(cls, '__class__') \
and \
('__dict__' in dir(cls) or hasattr(cls, '__slots__'))


class new_style(object):
pass

class old_style():
pass

print is_new_style(int)
print is_new_style(new_style)
print is_new_style(old_style)

Python 2.6 的输出:

False
True
False

这里有一个不同的方法:

def is_new_style(cls):
return str(cls).startswith('<class ')

关于python - 识别变量是Python中的新型类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2654622/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com