Home>

I would like to know how to add a method for a built-in class.
I'd like to add a new method to the str object, can't I do that? I was able to inherit the class, but I would like to add a method to the str type itself.

"String". I want to make it like my own method ().
Corresponding source code
class MyObject (str):
    def len (self):
        return len (self)
MyObject ("I am not panda."). Len ()
What I tried

I tried google, but I could only find articles such as class inheritance.

Supplementary information (FW/tool version, etc.)

The development environment is Colaboratotry.

  • Answer # 1

    Not for beginnersBut you can do it.

    First, import the forbiddenfruit library. You can install it with pip as usual.

    next,forbiddenfruit.curseAssigns a function to the attribute value of the built-in class with.

    You will be able to call the function with that attribute value.

    import forbiddenfruit
    def print_length (self):
        print (f "'{self}' length: {len (self)}")
    forbiddenfruit.curse (str, "print_length", print_length)
    "abcde" .print_length ()
    'abcde' length: 5

    Congrats. The forbidden fruit curse made it harder for others to understand the code.