【问题标题】:How to add my own method to the built-in str type?如何将我自己的方法添加到内置的 str 类型中?
【发布时间】:2015-03-07 09:33:17
【问题描述】:
def change(s):
    result=""
    for index,item in enumerate(s):
        if(index%2 !=0): result=result+item
    return(result)

此函数可以将字符串中的所有偶数字符提取到一个新字符串中:

>>> x="hallo world"
>>> change(x)
'al ol'
  1. 如何使它成为str 类的方法?当你在 Python 控制台中输入x.change() 时,我会得到与change(x) 相同的输出。 x.change() 将得到 'al ol'

  2. dir(x) 将在输出中得到'change',例如:

    ['__add__', '__class__', ...omitted..., 'zfill', 'change'] 
    

【问题讨论】:

  • 不确定,但您可以创建自己的模块,其名称与 sting 不同,并将其保存在 /usr/lib/python2.7/ 或 lib 目录中。
  • 我将它们称为字符串中的奇数字符,因为 Python 使用基于 0 的索引。另外,我意识到这只是自定义方法的一个示例,但是 FWIW 您可以执行 change() 方法对切片所做的操作:"hallo world"[1::2] -> 'al ol'

标签: python string class methods


【解决方案1】:

你不能这样做。好吧,至少不是直接的。 Python 不允许您将自定义方法/属性添加到内置类型。这只是语言的规律。

您可以通过subclassing(继承自)str 创建自己的字符串类型:

class MyStr(str):
    def change(self): # 's' argument is replaced by 'self'
        result=""
        for index,item in enumerate(self): # Use 'self' here instead of 's'
            if(index%2 !=0): result=result+item
        return(result)

演示:

>>> class MyStr(str):
...     def change(self):
...         result=""
...         for index,item in enumerate(self):
...             if(index%2 !=0): result=result+item
...         return(result)
...
>>> x = MyStr("hallo world")
>>> x
'hallo world'
>>> x.change()
'al ol'
>>> 'change' in dir(x)
True
>>>

新的MyStr 类在各方面的行为都与普通的str 类相同。事实上,它拥有str 上的所有功能:

>>> x = MyStr("hallo world")
>>> x.upper()
'HALLO WORLD'
>>> x.split()
['hallo', 'world']
>>>

两者的唯一区别是MyStr多了一个change方法。

【讨论】:

  • 另外,为了澄清,任何创建的字符串文字永远不会是MyStr的实例。
  • 由 str 类创建的任何字符串文字都将是 str 的实例,绝不是 MyStr 的实例。 >>> x1=str("haha1") >>> isinstance(x1,str) True >>> isinstance(x1,MyStr) False MyStr 类创建的任何字符串文字都将是 str 的实例或 MyStr 的实例. >>> x2=MyStr("haha2") >>> isinstance(x2,MyStr) True >>> isinstance(x2,str) True
  • @it_is_a_literature - 是的,这是意料之中的,因为MyStrstr 的子类。 isinstance 考虑了继承。如果您需要直接测试,您可以随时使用type(x) is MyStr。但请注意,很少需要这样做。
猜你喜欢
  • 2012-10-07
  • 2011-06-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-20
  • 2010-09-22
相关资源
最近更新 更多