Bestätigen Sie mit isinstance()
In diesem Schritt lernen Sie, wie Sie die isinstance()-Funktion in Python verwenden, um zu prüfen, ob ein Objekt eine Instanz einer bestimmten Klasse ist. Dies ist eine weitere Möglichkeit, zu bestätigen, ob eine Variable einen Boolean-Wert enthält. Die isinstance()-Funktion nimmt zwei Argumente entgegen: das zu überprüfende Objekt und die Klasse, gegen die geprüft werden soll. Sie gibt True zurück, wenn das Objekt eine Instanz der Klasse ist, andernfalls False.
Lassen Sie uns isinstance() verwenden, um zu prüfen, ob unsere Variablen Booleans sind:
-
Öffnen Sie die Datei boolean_example.py im Verzeichnis ~/project mit dem VS Code-Editor.
-
Ändern Sie die Datei boolean_example.py, um die isinstance()-Funktion einzubeziehen:
## Assign True to a variable
is_active = True
## Assign False to a variable
is_admin = False
## Print the values
print("Is active:", is_active)
print("Is admin:", is_admin)
## Comparison operations
x = 10
y = 5
is_greater = x > y ## True because 10 is greater than 5
is_equal = x == y ## False because 10 is not equal to 5
print("Is x greater than y:", is_greater)
print("Is x equal to y:", is_equal)
## Check the types of the variables
print("Type of is_active:", type(is_active))
print("Type of is_greater:", type(is_greater))
print("Type of x:", type(x))
## Check if the variables are instances of the bool class
print("is_active is an instance of bool:", isinstance(is_active, bool))
print("x is an instance of bool:", isinstance(x, bool))
-
Speichern Sie die Datei.
-
Führen Sie das Skript mit dem Befehl python im Terminal aus:
python ~/project/boolean_example.py
Sie sollten die folgende Ausgabe sehen:
Is active: True
Is admin: False
Is x greater than y: True
Is x equal to y: False
Type of is_active: <class 'bool'>
Type of is_greater: <class 'bool'>
Type of x: <class 'int'>
is_active is an instance of bool: True
x is an instance of bool: False
Wie Sie sehen können, gibt isinstance(is_active, bool) True zurück, da is_active ein Boolean-Wert ist, während isinstance(x, bool) False zurückgibt, da x eine Ganzzahl ist. Die isinstance()-Funktion ist nützlich, um zu prüfen, ob eine Variable zu einer bestimmten Klasse gehört und bietet eine robuster Möglichkeit, Datentypen zu überprüfen.