Home >Backend Development >Python Tutorial >In Python, __subclasscheck__ and __subclasshook__ are two special methods

In Python, __subclasscheck__ and __subclasshook__ are two special methods

PHPz
PHPzforward
2023-09-14 12:37:021995browse

In Python, __subclasscheck__ and __subclasshook__ are two special methods

Python is a universally adaptable and effective programming language that has long been popular. Python's object-oriented features allow for the implementation of high-quality features such as inheritance and polymorphism. In this article, we'll take a deep dive into two little-known but fascinating techniques that allow custom-designed inheritance checking in Python: subclasscheck and subclasshook.

What are Subclasscheck and Subclasshook?

In Python, it is not uncommon to determine whether a class is a subclass of another class by using the built-in issubclass() function. By default, this function examines the inheritance tree to determine connections between classes. However, Python also provides a way to override this default behavior using the unique methods subclasscheck and subclasshook.

  • __subclasscheck__(cls) Test whether a class is a subclass of all other classes by calling this technique using the issubclass() function. By default it returns the results of the usual inherited test, but it can be overridden to change this behavior.

  • __subclasshook__(cls) This method can be defined in the abstract base class (ABC) to customize the subclass check performed by issubclass() . It is called by the default implementation of subclasscheck in ABC.

Subclass hook method

To clearly understand how the subclasshook method works, let’s look at an example. Suppose we have an abstract base class called "Shape" which has two required methods: "area" and "perimeter". Any class that wishes to be considered a subclass of "Shape" must implement these methods.

Step 1 Use two specific methods to determine the abstract base class "Shape": "Area" and "Perimeter".

Step 2 Generate a custom class "Circle" that implements the specified methods "area" and "perimeter".

Step 3 Override the subclasshook method in the 'Shape' class to specify custom criteria for determining whether a class is a subclass. In this case, the criterion is that the class should have "Area" and "Perimeter" methods.

Step 4 Use the issubclass() function to test whether "Circle" is a subclass of "Shape". Using a custom subclass hook method, the result is "True" because "Circle" satisfies the custom condition.

Example

Now, let's create a custom class "Circle" that implements these methods -

from abc import ABCMeta, abstractmethod

class Shape(metaclass=ABCMeta):
   @abstractmethod
   def area(self):
      pass
   
   @abstractmethod
   def perimeter(self):
      pass
class Circle:
   def __init__(self, radius):
      self.radius = radius
   
   def area(self):
      return 3.14 * self.radius * self.radius
   
   def perimeter(self):
      return 2 * 3.14 * self.radius
print(issubclass(Circle, Shape))

Even if the "Circle" class implements the required method, the issubclass() function will still return "False" when checking whether "Circle" is a subclass of "Shape" -

Output

False

This is where the subclasshook method comes into play. We can override this method in the "Shape" class to specify custom criteria for determining whether a class is a subclass -

Example

class Shape(metaclass=ABCMeta):
   @abstractmethod
   def area(self):
      pass
   
   @abstractmethod
   def perimeter(self):
      pass
   
   @classmethod
   def __subclasshook__(cls, other):
      if cls is Shape:
         if all(hasattr(other, method) for method in ['area', 'perimeter']):
            return True
      return NotImplemented
print(issubclass(Circle, Shape))

Output

If we check if "Circle" is a subclass of "Shape", the output is as follows.

True

Subclass check method

In some cases, you may want to override the subclasscheck method itself instead of using a subclasshook. This can provide additional first-class granular control for inheritance testing. This is an example

Step 1 Determine the custom base class "CustomBase" that overrides the subclass check method. Instead of testing normal inheritance connections, we test whether the subclass has a callable "magic_attribute" method.

Step 2 Generate two classes, "DerivedWithMagic" and "DerivedWithoutMagic". The former has a 'magic_attribute' method, while the latter does not.

第 3 步  利用 issubclass() 函数来测试“DerivedWithMagic”和“DerivedWithoutMagic”是否是“CustomBase”的子类。对于“DerivedWithMagic”,结论为“True”,因为它具有所需的“magic_attribute”方法;对于“DerivedWithoutMagic”,结论为“False”,因为它不再具有指定的方法。

示例
class CustomBase:
   def __subclasscheck__(self, subclass):
      return (hasattr(sub

class, "magic_attribute") and
callable(getattr(subclass, "magic_attribute")))
class DerivedWithMagic:
def magic_attribute(self):
pass
class DerivedWithoutMagic:
pass
print(issubclass(DerivedWithMagic, CustomBase))
print(issubclass(DerivedWithoutMagic, CustomBase))

输出

如果我们检查“Circle”是否是“Shape”的子类,则输出如下。

True
False

实际用例

虽然 Python 中的默认继承机制适用于大多数场景,但在某些情况下,使用 __subclasscheck__ 和 __subclasshook__ 自定义子类检查可能会有所帮助 -

  • **协议执行**  通过使用这些方法,您可以强制执行子类必须遵守的某些协议。在前面的实例中,我们决定任何被视为“Shape”子类的类都必须执行“area”和“perimeter”方法。

  • **混合课程**  Mixin 类的创建是为了向其他类提供特定的行为,但它们并不意味着用作独立的类。您可以使用 __subclasscheck__ 或 __subclasshook__ 定义自定义继承策略,通过利用 mixin 作为子类来识别类,尽管它们不会立即继承它。

  • **松散耦合**  在某些情况下,最大限度地减少软件系统中组件之间的依赖关系是有益的。通过使用 __subclasscheck__ 和 __subclasshook__,您可以在类之间建立关系,而无需创建严格的继承层次结构。

结论

Python 中的 __subclasscheck__ 和 __subclasshook__ 方法提供了一种强大的方法来自定义继承检查。当您想要强制执行子类关系的特定要求或提供更灵活的继承结构时,这些方法特别有用。通过理解和利用这些特殊方法,您可以创建适应性更强、更健壮的 Python 程序。

The above is the detailed content of In Python, __subclasscheck__ and __subclasshook__ are two special methods. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete