如何将我自己的自定义属性添加到现有的内置 Python 类型?像一个字符串? [英] How do I add my own custom attributes to existing built-in Python types? Like a string?

查看:16
本文介绍了如何将我自己的自定义属性添加到现有的内置 Python 类型?像一个字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做这样的事情......

I want to do something like this...

def helloWorld():
  print "Hello world!"
str.helloWorld = helloWorld
"foo".helloWorld()

这会打印出Hello world!"

Which would print out "Hello world!"

参考 我可以添加内置 Python 类型的自定义方法/属性?

推荐答案

简而言之,你不能.Python 方式是继承 String 并从那里开始工作.

In short, you can't. The Python Way would be to subclass String and work from there.

这篇关于如何将我自己的自定义属性添加到现有的内置 Python 类型?像一个字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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