将自定义方法添加到字符串对象
可能重复:
我可以为内置Python类型添加自定义方法/属性吗?
在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 "", line 1, in x.sayHello() AttributeError: 'str' object has no attribute 'sayHello' >>> x = str("hello") >>> x.sayHello() hello is saying 'hello'
与此相当的普通Python是编写一个函数,它接受一个字符串作为它的第一个参数:
def sayhello(name): return "{} is saying hello".format(name) >>> sayhello('JOHN'.lower()) 'john is saying hello'
简单干净,简单。 并非一切都必须是方法调用。