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

20 投票
2 回答
22042 浏览
提问于 2025-04-16 10:00

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

在Ruby中,你可以用自定义的方法来覆盖任何内置对象的类,像这样:

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

puts 'JOHN'.downcase.sayHello   # >>> 'john is saying hello!'

那我在Python中怎么做呢?有没有正常的方法,还是只能用一些小技巧?

2 个回答

3

在Python中,通常我们会写一个函数,让它的第一个参数是一个字符串:

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

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

这样简单、干净又容易。并不是所有的事情都必须通过方法调用来完成。

29

你不能这样做,因为内置类型是用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): 来覆盖字符串类型,但这并不意味着你可以直接使用字面量 "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'

撰写回答