Module python_ast::tree::class_def
source · Expand description
A lot of languages, Python included, have a concept of a class, which combines the definition of a data type with an interface. In dynamic languages like Python, the class itself is a memory object, that can be permutated at runtime, however, this is probably usually a bad idea. Classes can contain:
- Methods (special functions)
- properties (attributes of the data element)
- Base classes (for inheritace)
- static data
- Additional classes
There is one construct in Rust that can emcompass all of these things: a module. So, we use modules to model classes following these rules:
- The module is given the name of the class. Contrary to other Rust modules, this is typically SnakeCase.
- The main data type defined by the class is a struct inside the module, and called Data.
- The Data struct can take two forms: a. If the properties of the class can be fully inferred, Data will be a simple struct and the attributes will be defined as fields of the struct. b. If the properties of the class cannot be fully inferred, such as if the class is accessed as a dictionary, Data will be a HashMap<String, _>, and the values will be accessed through it.
- Static data will be declared with lazy_static inside the module.
- Additional classes will be nested inside the module, and therefore they appear as modules inside a module.
- Each class also contains a trait, named Cls, which is used in inheritance.
- Each method of the class in Python will be translated to have a prototype in Cls. If it is possible to implement the method as a default method, it will be, otherwise (if the method refers to attributes of the class), a prototype will be added to Cls, and the implementation will be done inside an impl Cls for Data block.
- Cls will implement Clone, Default.