python - 将自定义方法添加到字符串对象

标签 python ruby

<分区>

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'

关于python - 将自定义方法添加到字符串对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4699179/

相关文章:

python - 了解 Pytorch 网格示例

python - python 生成器/协程中的值丢失

ruby - Ruby 在某处是否有跨平台 EOL 常量?

ruby - Travis-ci 构建失败,rake 中止!加载错误 : cannot load such file -- rspec/core/rake_task

python - 如何加速python网络?

python - 用于创建动画时,变量名后的逗号在 python 中意味着什么?

python - 接近 0.05 的舍入从结果中删除一位

ruby-on-rails - 在 script\console 中快速调试辅助方法

ruby-on-rails - 如何从 Ruby 数组创建平均值?

ruby-on-rails - 在 VS Code 中找不到 'ruby-debug-ide'