向字符串对象添加自定义方法 [英] Add custom method to string object
问题描述
可能的重复:
我可以向内置添加自定义方法/属性吗?在 Python 类型中?
在 Ruby 中,您可以使用自定义方法覆盖任何内置对象类,如下所示:
class 字符串明确说你好return self+"就是打招呼!"结尾结尾puts 'JOHN'.downcase.sayHello # >>>约翰在打招呼!"
我如何在 python 中做到这一点?有正常的方法还是只是黑客?
你不能,因为内置类型是用 C 编码的.你可以做的是子类化类型:
类字符串(str):def sayHello(self):打印(自我,说'你好'")
测试:
<预><代码>>>>x = string("测试")>>>X'测试'>>>x.sayHello()测试说你好"您也可以使用 class str(str):
覆盖 str 类型,但这并不意味着您可以使用文字 "test"
,因为它正在链接到内置的 str
.
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?
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'
这篇关于向字符串对象添加自定义方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!