Обложка канала

Библиотека Python разработчика

20835 @BookPython

Библиотека Python разработчика. Книги по программированию на Python.

Библиотека Python разработчика

4 года назад
Открыть в
There are two concepts with similar names that can be easily confused: overriding and overloading. Overriding happens when a child class defines a method that is already provided by its parents effectively replacing it. In some languages you have to explicitly mark the overriding method (C# requires the override modifier), in some languages it's optional (the @Override annotation in Java). Python doesn't require any special modifier nor does it have a standard way to mark such methods (some people like to use a custom @override decorator that does virtually nothing, just for the sake of readability). Overloading is another story. Overloading is having multiple functions with the same name but different signatures. It's supported by languages like Java and C++ and is often used as a way to provide default arguments: class Foo { public static void main(String[] args) { System.out.println(Hello()); } public static String Hello() { return Hello("world"); } public static String Hello(String name) { return "Hello, " + name; } } Python doesn't support finding functions by their signatures, only be their names. You can write code that analyzes the types and number of arguments explicitly. That usually looks clumsy and generally is not a nice thing to do: def quadrilateral_area(*args): if len(args) == 4: quadrilateral = Quadrilateral(*args) elif len(args) == 1: quadrilateral = args[0] else: raise TypeError() return quadrilateral.area() If you need type hints for this, the typing module can help you with the @overload decorator: from typing import overload @overload def quadrilateral_area( q: Quadrilateral ) -> float: ... @overload def quadrilateral_area( p1: Point, p2: Point, p3: Point, p4: Point ) -> float: ... @BookPython