Type Checking

Open

9.1 The type() Function

Python has a bunch of built-in functions for checking the types and classes of objects. These functions are super handy for writing flexible and safe code that can handle different data types.

I'll tell you about the most popular ones: type(), isinstance(), issubclass(), and also some functions for type annotation like getattr() and hasattr().

The type() Function

The type() function returns the type of an object. You've worked with it before, right?

x = 10
print(type(x))  # Output: <class 'int'>

But here's something you might not know: you can use it to create new classes!

Creating a New Class

If you pass it three arguments, it'll create a new type (class).

The signature for this operation is:

type(name, bases, dict)

where:

  • name — the name of the class being created (a string).
  • bases — a tuple of base classes (parents) from which the new class inherits.
  • dict — a dictionary containing attributes and methods for the new class.

Creating a Simple Class:

MyClass = type('MyClass', (), {'say_hello': lambda self: print("Hello!")})

# Create an instance of the class
instance = MyClass()
instance.say_hello()  # Output: Hello!

You can even make something more complex:

MyClass = type('MyClass', (), {
    'attribute': 42,
    '__init__': lambda self, value: setattr(self, 'value', value),
    'display_value': lambda self: print(self.value)
})

# Create an instance of the class
instance = MyClass(10)
print(instance.attribute)  # Output: 42
instance.display_value()  # Output: 10

So now you can not only determine the type of an object but also create a class, spawn some objects, and then determine their types.

9.2 The isinstance() Function

The isinstance() Function is a built-in function in Python used to check if an object belongs to a particular class or a tuple of classes. It returns True if the object is an instance of the specified class or any of the classes in the tuple, and False otherwise.

The signature and parameters:

isinstance(object, classinfo)

where:

  • object — the object whose class membership you want to check.
  • classinfo — a class, type, or a tuple of classes and types against which the object will be checked.

Usage examples:

Checking membership of a single class

x = 10
print(isinstance(x, int))  # Output: True

y = "Hello"
print(isinstance(y, str))  # Output: True

Checking membership of multiple classes — at least one of them:

x = 10
print(isinstance(x, (int, float)))  # Output: True

y = "Hello"
print(isinstance(y, (int, str)))  # Output: True

z = 3.14
print(isinstance(z, (int, str)))  # Output: False

Checking membership of custom classes

class Animal:
    pass

class Dog(Animal):
    pass

dog = Dog()

print(isinstance(dog, Dog))  # Output: True
print(isinstance(dog, Animal))  # Output: True

Unlike direct type comparison using type(), isinstance() correctly handles inheritance, checking for membership of an object in any class in the hierarchy.

9.3 The issubclass() Function

The issubclass() Function is a built-in function in Python used to check whether a specified class is a subclass of another class or any class in a tuple. It returns True if the first argument is indeed a subclass of the second, and False otherwise.

The signature and parameters:

issubclass(class, classinfo)

where:

  • class — the class whose membership to a class or classes needs to be checked.
  • classinfo — a class, type, or a tuple of classes and types against which the first argument will be checked.

Usage examples:

Checking membership of a single class

class Animal:
    pass

class Dog(Animal):
    pass

print(issubclass(Dog, Animal))  # Output: True
print(issubclass(Animal, Dog))  # Output: False

Checking membership of multiple classes — at least one:

class Animal:
    pass

class Dog(Animal):
    pass

class Cat(Animal):
    pass

print(issubclass(Dog, (Animal, Cat)))  # Output: True
print(issubclass(Dog, (Cat,)))  # Output: False

Examples with custom classes

Inheritance from built-in classes

class MyInt(int):
    pass

print(issubclass(MyInt, int))  # Output: True
print(issubclass(int, MyInt))  # Output: False

Inheritance hierarchy

class A:
    pass

class B(A):
    pass

class C(B):
    pass

print(issubclass(C, A))  # Output: True
print(issubclass(C, B))  # Output: True
print(issubclass(B, A))  # Output: True
print(issubclass(A, C))  # Output: False

Benefits of using issubclass()

Checking class hierarchy: issubclass() allows checking class hierarchy, which is useful for ensuring correct inheritance and code structure.

Flexibility: The function supports checking against both a single class or a tuple of classes, making it flexible for use in various scenarios.

Handy for metaprogramming: issubclass() is often used in metaprogramming and when writing code that deals with dynamic types and classes. But we'll talk about that much later :)

2
Task
Python SELF EN,  16 level,  2 lecture
Locked
Pets.
Pets.
2
Task
Python SELF EN,  16 level,  2 lecture
Locked
Fleet of vehicles.
Fleet of vehicles.
Комментарии
  • популярные
  • новые
  • старые
Для того, чтобы оставить комментарий Вы должны sign in
This page has no comments yet