【问题标题】:Add custom method to string object [duplicate]向字符串对象添加自定义方法[重复]
【发布时间】:2011-06-09 14:37:01
【问题描述】:

可能重复:
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 中做到这一点?有正常的方法还是只是黑客?

【问题讨论】:

  • 刚刚在stackoverflow.com/questions/4698493/… 中回答了这个问题。建议关闭。
  • Monkeypatching 是可能的,但有限制,正如那个问题(甚至更多)所指出的那样。我建议只定义一个执行此操作的“免费”函数。

标签: python ruby


【解决方案1】:

普通的 Python 等价于编写一个以字符串作为第一个参数的函数:

def sayhello(name):
    return "{} is saying hello".format(name)

>>> sayhello('JOHN'.lower())
'john is saying hello'

简单干净容易。并非一切都必须是方法调用。

【讨论】:

  • 这种方式的缺点是不能写mutator方法。例如,今天我想要一个方法str.startswithThenRemove(p) 改变str 以删除可选前缀p,然后如果找到前缀则返回True,如果找不到则返回Falseif option.startswithThenRemove("--foo="): handleFoo(option)。在 Python 中你不能以任何简单的方式做到这一点(但请参阅 stackoverflow.com/a/1551223/1424877)。
  • 即使您可以向字符串添加自定义方法,您仍然无法编写 mutator 方法:Python 字符串是不可变的。
【解决方案2】:

你不能,因为内置类型是用 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'

【讨论】:

    猜你喜欢
    • 2011-09-10
    • 2014-10-24
    • 1970-01-01
    • 2012-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-17
    相关资源
    最近更新 更多