Add custom method to string object [duplicate]

You can’t because the builtin-types are coded in C. What you can do is subclass the type:

class string(str):
    def sayHello(self):
        print(self, "is saying 'hello'")

Test:

>>> x = string("test")
>>> x
'test'
>>> x.sayHello()
test is saying 'hello'

You could also overwrite the str-type with class str(str):, but that doesn’t mean you can use the literal "test", because it is linking to the builtin str.

>>> x = "hello"
>>> x.sayHello()
Traceback (most recent call last):
  File "<pyshell#10>", line 1, in <module>
    x.sayHello()
AttributeError: 'str' object has no attribute 'sayHello'
>>> x = str("hello")
>>> x.sayHello()
hello is saying 'hello'

Leave a Comment