변수가 클래스인지 아닌지 확인하는 방법?
변수가 클래스인지 아닌지 확인하는 방법이 궁금합니다 (인스턴스 아님!).
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
인지 아닌지 여부를 반환 합니다 .X
False
이 검사는 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
'Programing' 카테고리의 다른 글
AngularJS에서 HTTP 'Get'서비스 응답을 캐시 하시겠습니까? (0) | 2020.04.30 |
---|---|
직렬화 할 수없는 작업 : 객체가 아닌 클래스에서만 클로저 외부에서 함수를 호출 할 때 java.io.NotSerializableException (0) | 2020.04.30 |
PHP에서 yield는 무엇을 의미합니까? (0) | 2020.04.30 |
Jest를 사용하여 ES6 모듈 가져 오기를 어떻게 조롱 할 수 있습니까? (0) | 2020.04.30 |
MySQL : DISTINCT 값 발생 횟수 계산 (0) | 2020.04.30 |