Adding a custom method to a string object

Possible duplicate:
Can I add my own methods / attributes to Python built-in types?

In Ruby, you can override any built-in class of an object using a custom method, for example:

class String def sayHello return self+" is saying hello!" end end puts 'JOHN'.downcase.sayHello # >>> 'john is saying hello!' 

How can i do this in python? Is there a regular way or just hacks?

+6
python ruby
source share
2 answers

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' 
+11
source share

The normal Python equivalent for this is to write a function that takes a string as the first argument:

 def sayhello(name): return "{} is saying hello".format(name) >>> sayhello('JOHN'.lower()) 'john is saying hello' 

Simple and simple. Not everything should be a method call.

+3
source share

All Articles