Earlier we learned how to create a new Python Type for a Delphi Record using the TPythonType component’s property TheType. It’s also necessary to learn how to use Delphi classes for creating a new Python Type using Python4Delphi component’s property PyObjectClass. You can also use Python4Delphi with C++Builder. This post will help to understand that.
Prerequisites: Download and install the latest Python for your platform. Follow the Python4Delphi installation instructions mentioned here. Alternatively, you can check out this video Getting started with Python4Delphi.
Components used in Python4Delphi Demo8 Sample App:
- TPythonEngine: A collection of relatively low-level routines for communicating with Python, creating Python types in Delphi, etc. It’s a singleton class.
- TPythonGUIInputOutput: Inherited from TPythonInputOutput (which works as a console for python outputs) Using this component Output property you can associate the Memo component to show the Output.
- TPythonModule: It’s inherited from TMethodsContainer class allows creating modules by providing a name. You can use routines AddMethod, AddMethodWithKW, AddDelphiMethod, AddDelphiMethodWithKeywords to add a method which should be type compatible with this routine parameter. You can create events using the Events property.
- TPythonType: This component helps to create a new python type in Delphi which is inherited from the hierarchy of classes (set of APIs to create, manage methods, and members).
- TMemo: A multiline text editing control, providing text scrolling. The text in the memo control can be edited as a whole or line by line.
You can find the Python4Delphi Demo8 sample project from the extracted repository ..\Python4Delphi\Demos\Demo08.dproj. Open this project in RAD Studio 10.4.1 and run the application.
Implementation Details:
- PythonEngine1 provides the connection to Python or rather the Python API. This project uses Python3.9 which can be seen in TPythonEngine DllName property. It Is assigned with InitScript which import sys module and prints the Python.Dll version, copyright information to Memo2. import sys print(“Python Dll: “, sys.version) print(sys.copyright) print()
- PythonGUIInputOutput1 provides a conduit for routing input and output between the Graphical User Interface (GUI) and the currently
executing Python script. - In this sample, Created a Delphi class(TPyPoint) implementing a new Python type. It is derived from TPyObject. It overrides some methods, like the constructors, the RegisterMethods, and the type services’ virtual methods. During PythonType1 initialization assign the property PyObjectClass with the class TPyPoint.
- PythonModule1 with Module name spam is created.
- On Clicking Execute Button the below script is executed.
Check some of the tutorials available for Python4Delphi here