Add custom method to string object [duplicate]
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 sayHell开发者_运维技巧o
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?
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'
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.
精彩评论