Create Python classes in JavaScript using `PyClass`
masterYou can extend a Python class in JavaScript by creating a class that extends PyClass. This allows you to add JavaScript methods to a Python object or override existing ones.
Lifecycle and Methods
constructor(superclass: PythonRef = null, superArguments = [], superKwargs = {}): Used to initialize JS properties and specify the Python superclass. The constructor is called before the Python__init__method.init(): This method is called after the Python superclass has been initialized. Variables defined here exist on the Python side but remain accessible from JS.this.parent: Acts likesuper.in standard JavaScript, allowing you to call methods on the Python superclass to avoid recursion.
Performance Note
While variables can exist on both sides, accessing a variable frequently across the bridge incurs overhead. For high-frequency access, keep the variable on the same side as the logic using it.
import { python, PyClass } from 'pythonia'
const calc = await python('./calc.py')
class MyCalculator extends PyClass {
constructor() {
// super(PythonClass, positionalArgs, keywordArgs)
super(calc.Calc, [true], { integers: false })
}
async mul (a, b) {
let res = a
for (let i = 1; i < b; i++) {
res = await this.add(res, b)
}
return res
}
async div(a, b) {
// Call the superclass's div() using this.parent
return await this.parent.div(a, b)
}
}
// Instantiate the class
const calculator = await MyCalculator.init()