클래스의 Python 검사 인스턴스
객체가 클래스의 인스턴스인지 확인하는 방법이 있습니까? 구체적인 클래스의 인스턴스가 아니라 모든 클래스의 인스턴스입니다.
객체가 클래스, 모듈, 트레이스 백 등이 아닌지 확인할 수 있지만 간단한 솔루션에 관심이 있습니다.
isinstance()
여기 당신의 친구입니다. 부울을 반환하며 다음과 같은 방식으로 유형을 확인하는 데 사용할 수 있습니다.
if isinstance(obj, (int, long, float, complex)):
print obj, "is a built-in number type"
if isinstance(obj, MyClass):
print obj, "is of type MyClass"
도움이 되었기를 바랍니다.
isinstance()
내장 기능 을 사용해 보셨습니까 ?
또한 hasattr(obj, '__class__')
개체가 일부 클래스 유형에서 인스턴스화되었는지 확인할 수도 있습니다 .
class test(object): pass
type(test)
보고
<type 'type'>
instance = test()
type(instance)
보고
<class '__main__.test'>
그래서 그것이 그들을 구별하는 한 가지 방법입니다.
def is_instance(obj):
import inspect, types
if not hasattr(obj, '__dict__'):
return False
if inspect.isroutine(obj):
return False
if type(obj) == types.TypeType: # alternatively inspect.isclass(obj)
# class type
return False
else:
return True
나는 늦었다. 어쨌든 이것이 효과가 있다고 생각하십시오.
is_class = hasattr(obj, '__name__')
나는 이것에 대해 꽤 늦었다 고 생각하고 infact는 같은 문제로 고심하고 있었다. 그래서 여기에 저에게 효과가 있습니다.
>>> class A:
... pass
...
>>> obj = A()
>>> hasattr(obj, '__dict__')
True
>>> hasattr((1,2), '__dict__')
False
>>> hasattr(['a', 'b', 1], '__dict__')
False
>>> hasattr({'a':1, 'b':2}, '__dict__')
False
>>> hasattr({'a', 'b'}, '__dict__')
False
>>> hasattr(2, '__dict__')
False
>>> hasattr('hello', '__dict__')
False
>>> hasattr(2.5, '__dict__')
False
>>>
나는 이것을 파이썬 3과 2.7 모두에서 테스트했습니다.
나는 이것에서 비슷한 문제가 나를 위해 일하는 것으로 판명되었습니다.
def isclass(obj):
return isinstance(obj, type)
It's a bit hard to tell what you want, but perhaps inspect.isclass(val)
is what you are looking for?
or
import inspect
inspect.isclass(myclass)
Here's a dirt trick.
if str(type(this_object)) == "<type 'instance'>":
print "yes it is"
else:
print "no it isn't"
Had to deal with something similar recently.
import inspect
class A:
pass
def func():
pass
instance_a = A()
def is_object(obj):
return inspect.isclass(type(obj)) and not type(obj) == type
is_object(A) # False
is_object(func) # False
is_object(instance_a) # True
Yes. Accordingly, you can use hasattr(obj, '__dict__')
or obj is not callable(obj)
.
참고URL : https://stackoverflow.com/questions/14549405/python-check-instances-of-classes
'Development Tip' 카테고리의 다른 글
Git에서 분기의 해시를 찾는 방법은 무엇입니까? (0) | 2020.11.27 |
---|---|
탭 / 브라우저 닫기 전 확인 (0) | 2020.11.27 |
초기화, 정의, 변수 선언의 차이점 (0) | 2020.11.27 |
이해하려고?. (0) | 2020.11.27 |
VBscript에서 명령 줄 인수 사용 (0) | 2020.11.27 |