type(), isinstance() na získanie a určenie typu v jazyku Python

obchodné

V jazyku Python sa vstavané funkcie type() a isinstance() používajú na získanie a kontrolu typu objektu, napríklad premennej, a na určenie, či je určitého typu.

Tu je vysvetlený nasledujúci obsah spolu so vzorovým kódom.

  • Získanie a kontrola typu objektu:type()
  • Určenie typu objektu:type(),isinstance()
    • Určenie typu pomocou funkcie type()
    • Určenie typu pomocou funkcie isinstance()
    • Rozdiel medzi funkciami type() a isinstance()

Namiesto zisťovania typu objektu je možné použiť spracovanie výnimiek alebo vstavanú funkciu hasattr() na zistenie, či má objekt správne metódy a atribúty.

Získanie a kontrola typu objektu: typ()

type(object) je funkcia, ktorá vráti typ objektu odovzdaného ako argument. Túto funkciu možno použiť na zistenie typu objektu.

print(type('string'))
# <class 'str'>

print(type(100))
# <class 'int'>

print(type([0, 1, 2]))
# <class 'list'>

Návratovou hodnotou funkcie type() je objekt typu, napríklad str alebo int.

print(type(type('string')))
# <class 'type'>

print(type(str))
# <class 'type'>

Určenie typu objektu: type(), isinstance()

Na určenie typu použite type() alebo isinstance().

Určenie typu pomocou funkcie type()

Porovnaním návratovej hodnoty funkcie type() s ľubovoľným typom možno určiť, či je objekt ľubovoľného typu.

print(type('string') is str)
# True

print(type('string') is int)
# False
def is_str(v):
    return type(v) is str

print(is_str('string'))
# True

print(is_str(100))
# False

print(is_str([0, 1, 2]))
# False

Ak chcete určiť, či ide o jeden z viacerých typov, použite operátor in a tuple alebo zoznam viacerých typov.

def is_str_or_int(v):
    return type(v) in (str, int)

print(is_str_or_int('string'))
# True

print(is_str_or_int(100))
# True

print(is_str_or_int([0, 1, 2]))
# False

Je tiež možné definovať funkcie, ktoré menia spracovanie v závislosti od typu argumentu.

def type_condition(v):
    if type(v) is str:
        print('type is str')
    elif type(v) is int:
        print('type is int')
    else:
        print('type is not str or int')

type_condition('string')
# type is str

type_condition(100)
# type is int

type_condition([0, 1, 2])
# type is not str or int

Určenie typu pomocou funkcie isinstance()

isinstance(object, class) je funkcia, ktorá vráti true, ak je objekt prvého argumentu inštanciou typu alebo podtriedy druhého argumentu.

Druhým argumentom môže byť tuple typov. Ak je to inštancia niektorého z typov, vráti sa hodnota true.

print(isinstance('string', str))
# True

print(isinstance(100, str))
# False

print(isinstance(100, (int, str)))
# True

Funkciu podobnú príkladu určenia typu pomocou funkcie type() možno napísať takto

def is_str(v):
    return isinstance(v, str)

print(is_str('string'))
# True

print(is_str(100))
# False

print(is_str([0, 1, 2]))
# False
def is_str_or_int(v):
    return isinstance(v, (int, str))

print(is_str_or_int('string'))
# True

print(is_str_or_int(100))
# True

print(is_str_or_int([0, 1, 2]))
# False
def type_condition(v):
    if isinstance(v, str):
        print('type is str')
    elif isinstance(v, int):
        print('type is int')
    else:
        print('type is not str or int')

type_condition('string')
# type is str

type_condition(100)
# type is int

type_condition([0, 1, 2])
# type is not str or int

Rozdiel medzi funkciami type() a isinstance()

Rozdiel medzi type() a isinstance() je v tom, že isinstance() vracia true pre inštancie podtried, ktoré dedia triedu zadanú ako druhý argument.

Napríklad sú definované tieto nadtriedy (základné triedy) a podtriedy (odvodené triedy)

class Base:
    pass

class Derive(Base):
    pass

base = Base()
print(type(base))
# <class '__main__.Base'>

derive = Derive()
print(type(derive))
# <class '__main__.Derive'>

Určenie typu pomocou funkcie type() vráti true len vtedy, keď sa typy zhodujú, ale funkcia isinstance() vráti true aj pre nadtriedy.

print(type(derive) is Derive)
# True

print(type(derive) is Base)
# False

print(isinstance(derive, Derive))
# True

print(isinstance(derive, Base))
# True

Aj pri štandardných typoch, napríklad pri logickom type bool (true,false), je potrebné dávať pozor. bool je podtrieda typu integer, takže funkcia isinstance() vracia true aj pre int, od ktorého je zdedená.

print(type(True))
# <class 'bool'>

print(type(True) is bool)
# True

print(type(True) is int)
# False

print(isinstance(True, bool))
# True

print(isinstance(True, int))
# True

Ak chcete určiť presný typ, použite type(); ak chcete určiť typ so zohľadnením dedičnosti, použite isinstance().

Vstavaná funkcia issubclass() slúži aj na určenie, či je trieda podtriedou inej triedy.

print(issubclass(bool, int))
# True

print(issubclass(bool, float))
# False
Copied title and URL