0

Prototype in Python3

Hi! How can I add functions to an existing class? I want to recreate something like this: (JS) String.prototype.red = () => {...} How can I add a method to the str class?

29th Nov 2020, 12:24 PM
Csongor Kertesi
Csongor Kertesi - avatar
2 ответов
+ 4
Python inheritance model is class based not prototype based like JavaScript. So your question should be how you can extend a data class in Python. The answer to that is INHERITANCE. class A (B): # A extends B It is more tricky with str because str is not a Python type. It is implemented in C. It is a special case constructor. Your best bet is composition. You may store the str object as a hidden field(double underscores) for your new data type and indirectly work with it.
29th Nov 2020, 12:38 PM
Ore
Ore - avatar
+ 1
Ore Thank you
29th Nov 2020, 12:42 PM
Csongor Kertesi
Csongor Kertesi - avatar