Programing

변수가 클래스인지 아닌지 확인하는 방법?

lottogame 2020. 4. 30. 07:25
반응형

변수가 클래스인지 아닌지 확인하는 방법?


변수가 클래스인지 아닌지 확인하는 방법이 궁금합니다 (인스턴스 아님!).

isinstance(object, class_or_type_or_tuple)이 작업을 수행 하기 위해 함수를 사용하려고 시도했지만 클래스에 어떤 유형이 있는지 알 수 없습니다.

예를 들어 다음 코드에서

class Foo: pass  
isinstance(Foo, **???**) # i want to make this return True.

" class"를 ???로 바꾸려고했습니다. ,하지만 그것이 class파이썬의 키워드 라는 것을 깨달았습니다 .


더 나은 : inspect.isclass기능을 사용하십시오 .

>>> import inspect
>>> class X(object):
...     pass
... 
>>> inspect.isclass(X)
True

>>> x = X()
>>> isinstance(x, X)
True
>>> y = 25
>>> isinstance(y, X)
False

inspect.isclass는 아마도 최고의 솔루션 일 것입니다. 실제로 어떻게 구현되는지 쉽게 알 수 있습니다.

def isclass(object):
    """Return true if the object is a class.

    Class objects provide these attributes:
        __doc__         documentation string
        __module__      name of module in which this class was defined"""
    return isinstance(object, (type, types.ClassType))

>>> class X(object):
...     pass
... 
>>> type(X)
<type 'type'>
>>> isinstance(X,type)
True

isinstance(X, type)

클래스 True인지 아닌지 여부를 반환 합니다 .XFalse


이 검사는 Python 2.x 및 Python 3.x와 호환됩니다.

import six
isinstance(obj, six.class_types)

이것은 기본적으로 andrea_crotti 답변과 동일한 검사를 수행하는 래퍼 함수입니다.

예:

>>> import datetime
>>> isinstance(datetime.date, six.class_types)
>>> True
>>> isinstance(datetime.date.min, six.class_types)
>>> False

class Foo: is called old style class and class X(object): is called new style class.

Check this What is the difference between old style and new style classes in Python? . New style is recommended. Read about "unifying types and classes"


simplest way is to use inspect.isclass as posted in the most-voted answer.
the implementation details could be found at python2 inspect and python3 inspect.
for new-style class: isinstance(object, type)
for old-style class: isinstance(object, types.ClassType)
em, for old-style class, it is using types.ClassType, here is the code from types.py:

class _C:
    def _m(self): pass
ClassType = type(_C)

There are some working solutions here already, but here's another one:

>>> import types
>>> class Dummy: pass
>>> type(Dummy) is types.ClassType
True

참고URL : https://stackoverflow.com/questions/395735/how-to-check-whether-a-variable-is-a-class-or-not

반응형