You cannot, because the built-in types are encoded 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 can also overwrite the str type with class str(str): but this does not mean that you can use the literal "test" because it refers to the built-in 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'
Joschua
source share