IT

파이썬에서 객체의 유형을 비교하는 방법은 무엇입니까?

lottoking 2020. 6. 12. 08:33
반응형

파이썬에서 객체의 유형을 비교하는 방법은 무엇입니까?


기본적으로 나는 이것을하고 싶다 :

obj = 'str'
type ( obj ) == string

나는 시도했다 :

type ( obj ) == type ( string )

그리고 그것은 작동하지 않았다.

또한 다른 유형은 어떻습니까? 예를 들어, 나는 복제 할 수 없었다 NoneType.


isinstance()

귀하의 경우에는 isinstance("this is a string", str)을 반환 True합니다.

이것을 읽을 수도 있습니다 : http://www.canonical.org/~kragen/isinstance/


isinstance 공장:

if isinstance(obj, MyClass): do_foo(obj)

그러나 명심하십시오 : 오리처럼 보이고 오리처럼 들리면 오리입니다.

편집 : 없음 유형의 경우 간단하게 수행 할 수 있습니다.

if obj is None: obj = MyClass()

먼저 모든 유형 비교를 피하십시오. 그들은 매우, 매우 드물게 필요합니다. 때로는 함수에서 매개 변수 유형을 확인하는 데 도움이됩니다. 잘못된 유형의 데이터는 예외를 발생 시키므로 필요한 모든 것입니다.

모든 기본 변환 함수는 type 함수와 동일하게 매핑됩니다.

type(9) is int
type(2.5) is float
type('x') is str
type(u'x') is unicode
type(2+3j) is complex

다른 경우가 몇 가지 있습니다.

isinstance( 'x', basestring )
isinstance( u'u', basestring )
isinstance( 9, int )
isinstance( 2.5, float )
isinstance( (2+3j), complex )

BTW는 이러한 유형 검사가 필요하지 않습니다. None은 NoneType의 유일한 인스턴스입니다. None 객체는 싱글 톤입니다. 없음을 확인하십시오.

variable is None

BTW, 위의 일반적으로 사용하지 마십시오. 일반적인 예외와 파이썬의 고유 한 다형성을 사용하십시오.


다른 유형의 경우 유형 모듈을 확인하십시오 .

>>> import types
>>> x = "mystring"
>>> isinstance(x, types.StringType)
True
>>> x = 5
>>> isinstance(x, types.IntType)
True
>>> x = None
>>> isinstance(x, types.NoneType)
True

PS 유형 검사는 나쁜 생각입니다.


알려진 유형의 무언가가 있는 type(x) == type(y)트릭을 항상 사용할 수 있습니다 y.

# check if x is a regular string
type(x) == type('')
# check if x is an integer
type(x) == type(1)
# check if x is a NoneType
type(x) == type(None)

종종 최근의 파이썬에서 더 좋은 방법이 있습니다. 그러나 한 가지만 기억하고 싶다면 기억할 수 있습니다.

이 경우 더 좋은 방법은 다음과 같습니다.

# check if x is a regular string
type(x) == str
# check if x is either a regular string or a unicode string
type(x) in [str, unicode]
# alternatively:
isinstance(x, basestring)
# check if x is an integer
type(x) == int
# check if x is a NoneType
x is None

Note the last case: there is only one instance of NoneType in python, and that is None. You'll see NoneType a lot in exceptions (TypeError: 'NoneType' object is unsubscriptable -- happens to me all the time..) but you'll hardly ever need to refer to it in code.

Finally, as fengshaun points out, type checking in python is not always a good idea. It's more pythonic to just use the value as though it is the type you expect, and catch (or allow to propagate) exceptions that result from it.


You're very close! string is a module, not a type. You probably want to compare the type of obj against the type object for strings, namely str:

type(obj) == str  # this works because str is already a type

Alternatively:

type(obj) == type('')

Note, in Python 2, if obj is a unicode type, then neither of the above will work. Nor will isinstance(). See John's comments to this post for how to get around this... I've been trying to remember it for about 10 minutes now, but was having a memory block!


It is because you have to write

s="hello"
type(s) == type("")

type accepts an instance and returns its type. In this case you have to compare two instances' types.

If you need to do preemptive checking, it is better if you check for a supported interface than the type.

The type does not really tell you much, apart of the fact that your code want an instance of a specific type, regardless of the fact that you could have another instance of a completely different type which would be perfectly fine because it implements the same interface.

For example, suppose you have this code

def firstElement(parameter):
    return parameter[0]

Now, suppose you say: I want this code to accept only a tuple.

import types

def firstElement(parameter):
    if type(parameter) != types.TupleType:
         raise TypeError("function accepts only a tuple")
    return parameter[0]

This is reducing the reusability of this routine. It won't work if you pass a list, or a string, or a numpy.array. Something better would be

def firstElement(parameter):
    if not (hasattr(parameter, "__getitem__") and callable(getattr(parameter,"__getitem__"))):
        raise TypeError("interface violation")
    return parameter[0]

but there's no point in doing it: parameter[0] will raise an exception if the protocol is not satisfied anyway... this of course unless you want to prevent side effects or having to recover from calls that you could invoke before failing. (Stupid) example, just to make the point:

def firstElement(parameter):
    if not (hasattr(parameter, "__getitem__") and callable(getattr(parameter,"__getitem__"))):
        raise TypeError("interface violation")
    os.system("rm file")
    return parameter[0]

in this case, your code will raise an exception before running the system() call. Without interface checks, you would have removed the file, and then raised the exception.


I use type(x) == type(y)

For instance, if I want to check something is an array:

type( x ) == type( [] )

string check:

type( x ) == type( '' ) or type( x ) == type( u'' )

If you want to check against None, use is

x is None

Use str instead of string

type ( obj ) == str

Explanation

>>> a = "Hello"
>>> type(a)==str
True
>>> type(a)
<type 'str'>
>>>

i think this should do it

if isinstance(obj, str)

Type doesn't work on certain classes. If you're not sure of the object's type use the __class__ method, as so:

>>>obj = 'a string'
>>>obj.__class__ == str
True

Also see this article - http://www.siafoo.net/article/56


To get the type, use the __class__ member, as in unknown_thing.__class__

Talk of duck-typing is useless here because it doesn't answer a perfectly good question. In my application code I never need to know the type of something, but it's still useful to have a way to learn an object's type. Sometimes I need to get the actual class to validate a unit test. Duck typing gets in the way there because all possible objects have the same API, but only one is correct. Also, sometimes I'm maintaining somebody else's code, and I have no idea what kind of object I've been passed. This is my biggest problem with dynamically typed languages like Python. Version 1 is very easy and quick to develop. Version 2 is a pain in the buns, especially if you didn't write version 1. So sometimes, when I'm working with a function I didn't write, I need to know the type of a parameter, just so I know what methods I can call on it.

That's where the __class__ parameter comes in handy. That (as far as I can tell) is the best way (maybe the only way) to get an object's type.


Use isinstance(object, type). As above this is easy to use if you know the correct type, e.g.,

isinstance('dog', str) ## gives bool True

But for more esoteric objects, this can be difficult to use. For example:

import numpy as np 
a = np.array([1,2,3]) 
isinstance(a,np.array) ## breaks

but you can do this trick:

y = type(np.array([1]))
isinstance(a,y) ## gives bool True 

So I recommend instantiating a variable (y in this case) with a type of the object you want to check (e.g., type(np.array())), then using isinstance.


You can compare classes for check level.

#!/usr/bin/env python
#coding:utf8

class A(object):
    def t(self):
        print 'A'
    def r(self):
        print 'rA',
        self.t()

class B(A):
    def t(self):
        print 'B'

class C(A):
    def t(self):
        print 'C'

class D(B, C):
    def t(self):
        print 'D',
        super(D, self).t()

class E(C, B):
    pass

d = D()
d.t()
d.r()

e = E()
e.t()
e.r()

print isinstance(e, D) # False
print isinstance(e, E) # True
print isinstance(e, C) # True
print isinstance(e, B) # True
print isinstance(e, (A,)) # True
print e.__class__ >= A, #False
print e.__class__ <= C, #False
print e.__class__ <  E, #False
print e.__class__ <= E  #True

참고URL : https://stackoverflow.com/questions/707674/how-to-compare-type-of-an-object-in-python

반응형