Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add custom method to string object [duplicate]

Tags:

python

ruby

Possible Duplicate:
Can I add custom methods/attributes to built-in Python types?

In Ruby you can override any built-in object class with custom method, like this:

class String
  def sayHello
    return self+" is saying hello!"
  end
end                              

puts 'JOHN'.downcase.sayHello   # >>> 'john is saying hello!'

How can i do that in python? Is there a normally way or just hacks?

like image 724
nukl Avatar asked Jan 15 '11 10:01

nukl


2 Answers

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'
like image 124
Joschua Avatar answered Sep 19 '22 17:09

Joschua


The normal Python equivalent to this is to write a function that takes a string as it's first argument:

def sayhello(name):
    return "{} is saying hello".format(name)

>>> sayhello('JOHN'.lower())
'john is saying hello'

Simple clean and easy. Not everything has to be a method call.

like image 41
Duncan Avatar answered Sep 17 '22 17:09

Duncan