Possible Duplicate:
Can I add custom methods/attributes to built-in Python types?
在 Ruby 中,您可以使用自定义方法覆盖任何内置对象类,如下所示:
class String
def sayHello
return self+" is saying hello!"
end
end
puts 'JOHN'.downcase.sayHello # >>> 'john is saying hello!'
我怎样才能在 python 中做到这一点?有正常的方法还是只是黑客?
你不能,因为内置类型是用 C 编码的。你可以做的是子类化该类型:
class string(str):
def sayHello(self):
print(self, "is saying 'hello'")
测试:
>>> x = string("test")
>>> x
'test'
>>> x.sayHello()
test is saying 'hello'
你也可以用 class str(str):
覆盖 str 类型,但这并不意味着你可以使用文字 "test"
,因为它正在链接到内置的 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'