向字符串对象添加自定义方法

nuk*_*ukl 11 ruby python

可能重复:
我可以为内置Python类型添加自定义方法/属性吗?

在Ruby中,您可以使用自定义方法覆盖任何内置对象类,如下所示:

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

puts 'JOHN'.downcase.sayHello   # >>> 'john is saying hello!'
Run Code Online (Sandbox Code Playgroud)

我怎么能在python中做到这一点?有通常的方式或只是黑客?

Jos*_*hua 19

你不能因为内置类型用C编码.你可以做的是子类化:

class string(str):
    def sayHello(self):
        print(self, "is saying 'hello'")
Run Code Online (Sandbox Code Playgroud)

测试:

>>> x = string("test")
>>> x
'test'
>>> x.sayHello()
test is saying 'hello'
Run Code Online (Sandbox Code Playgroud)

你也可以用str覆盖str类型class 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'
Run Code Online (Sandbox Code Playgroud)