向字符串对象添加自定义方法 [英] Add custom method to string object

查看:52
本文介绍了向字符串对象添加自定义方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<块引用>

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

在 Ruby 中,您可以使用自定义方法覆盖任何内置对象类,如下所示:

class 字符串明确说你好return self+"就是打招呼!"结尾结尾puts 'JOHN'.downcase.sayHello # >>>约翰在打招呼!"

我如何在 python 中做到这一点?有正常的方法还是只是黑客?

解决方案

你不能,因为内置类型是用 C 编码的.你可以做的是子类化类型:

类字符串(str):def sayHello(self):打印(自我,说'你好'")

测试:

<预><代码>>>>x = string("测试")>>>X'测试'>>>x.sayHello()测试说你好"

您也可以使用 class str(str): 覆盖 str 类型,但这并不意味着您可以使用文字 "test",因为它正在链接到内置的 str.

<预><代码>>>>x = "你好">>>x.sayHello()回溯(最近一次调用最后一次):文件<pyshell#10>",第 1 行,在 <module> 中x.sayHello()AttributeError: 'str' 对象没有属性 'sayHello'>>>x = str("你好")>>>x.sayHello()你好是说你好"

Possible Duplicate:
Can I add custom methods/attributes to built-in Python types?

In Ruby you can override any built-in object class with custom method, like this:

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

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

How can i do that in python? Is there a normally way or just hacks?

解决方案

You can't because the builtin-types are coded in C. What you can do is subclass the type:

class string(str):
    def sayHello(self):
        print(self, "is saying 'hello'")

Test:

>>> x = string("test")
>>> x
'test'
>>> x.sayHello()
test is saying 'hello'

You could also overwrite the str-type with class str(str):, but that doesn't mean you can use the literal "test", because it is linking to the builtin 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'

这篇关于向字符串对象添加自定义方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆