2010-08-09 19 views
5

Ho bisogno di fare una cosa se args è integer e cosa ather se args è una stringa.Come verificare il tipo di variabile? Python

Come posso digitare il tipo? Esempio:

def handle(self, *args, **options): 

     if not args: 
      do_something() 
     elif args is integer: 
      do_some_ather_thing: 
     elif args is string: 
      do_totally_different_thing() 

risposta

13

Primo, *args è sempre un elenco. Vuoi controllare se il suo contenuto è stringhe?

import types 
def handle(self, *args, **options): 
    if not args: 
     do_something() 
    # check if everything in args is a Int 
    elif all(isinstance(s, types.IntType) for s in args): 
     do_some_ather_thing() 
    # as before with strings 
    elif all(isinstance(s, types.StringTypes) for s in args): 
     do_totally_different_thing() 

Esso utilizza types.StringTypes perché Python ha in realtà due tipi di stringhe: Unicode e stringhe di byte - questo modo sia di lavoro.

In Python3 i tipi predefiniti sono stati rimossi dalla libreria types e vi è un solo tipo di stringa. Ciò significa che i controlli tipo assomigliano a isinstance(s, int) e isinstance(s, str).

+0

il tuo diritto. È una lista. – Pol

+0

C'è qualche preferenza per l'uso di 'isinstance (s, types.IntType)' su solo 'isinstance (s, int)' o è solo per essere coerente con ciò che hai menzionato per i due tipi di stringhe? Solo curioso. –

+1

La tua soluzione non è compatibile con Python 3.1! – banx

0
type(variable_name) 

quindi è necessario utilizzare:

if type(args) is type(0): 
    blabla 

Sopra stiamo confrontando se il tipo di argomenti variabile è la stessa letterale 0, che è un numero intero, se si desidero sapere se per esempio il tipo è lungo, lo si confronta con type(0l), ecc.

+0

Non capisco. Come si usa? – Pol

+4

Ugh. 'type (2)' è 'int', ma comunque,' type' è Not Good Python – katrielalex

0

Se si sa che ci si aspetta un argomento intero/stringa, non si deve ingerirlo in *args. Non

def handle(self, first_arg = None, *args, **kwargs): 
    if isinstance(first_arg, int): 
     thing_one() 
    elif isinstance(first_arg, str): 
     thing_two() 
1

Si potrebbe anche provare a farlo in modo più Pythonic senza usare type o isinstance (preferito perché supporta l'ereditarietà):

if not args: 
    do_something() 
else: 
    try: 
     do_some_other_thing() 
    except TypeError: 
     do_totally_different_thing() 

Dipende, ovviamente, su ciò che do_some_other_thing() fa.

0

Nessuno ha parlato, ma il più facile chiedere perdono per principio si applica probabilmente da quando presumo vi ritroverete a fare qualcosa con quel numero intero:

def handle(self, *args, **kwargs): 
    try: 
     #Do some integer thing 
    except TypeError: 
     #Do some string thing 

Naturalmente se quella cosa intero sta modificando i valori nella tua lista, forse dovresti controllare prima. Naturalmente, se si desidera collegare attraverso args e fare qualcosa per gli interi e qualcos'altro per le stringhe:

def handle(self, *args, **kwargs): 
    for arg in args: 
     try: 
      #Do some integer thing 
     except TypeError: 
      #Do some string thing 

Naturalmente questo è anche supponendo che nessun altra operazione nel tentativo getterà un TypeError.

+0

effettivamente l'ho menzionato :) – systempuntoout

Problemi correlati