向字符串obj添加自定义方法

2024-05-29 12:01:03 发布

您现在位置:Python中文网/ 问答频道 /正文

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呢?有正常的方法还是黑客?


Tags: to方法addhelloiscustomcanattributes
2条回答

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

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

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

简单、干净、简单。不是所有的东西都必须是方法调用。

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

相关问题 更多 >

    热门问题