For example—say I want to add a helloWorld() method to Python's dict type. Can I do this?

JavaScript has a prototype object that behaves this way. Maybe it's bad design and I should subclass the dict object, but then it only works on the subclasses and I want it to work on any and all future dictionaries.

Here's how it would go down in JavaScript:

String.prototype.hello = function() {

alert("Hello, " + this + "!");

}

"Jed".hello() //alerts "Hello, Jed!"

解决方案

You can't directly add the method to the original type. However, you can subclass the type then substitute it in the built-in/global namespace, which achieves most of the effect desired. Unfortunately, objects created by literal syntax will continue to be of the vanilla type and won't have your new methods/attributes.

Here's what it looks like

# Built-in namespace

import __builtin__

# Extended subclass

class mystr(str):

def first_last(self):

if self:

return self[0] + self[-1]

else:

return ''

# Substitute the original str with the subclass on the built-in namespace

__builtin__.str = mystr

print str(1234).first_last()

print str(0).first_last()

print str('').first_last()

print '0'.first_last()

output = """

14

00

Traceback (most recent call last):

File "strp.py", line 16, in

print '0'.first_last()

AttributeError: 'str' object has no attribute 'first_last'

"""

python自定义类的属性_我可以将自定义方法/属性添加到内置Python类型吗?相关推荐

  1. python 模拟微信浏览器请求_使用Chrome修改user agent模拟微信内置浏览器

    很多时候,我们需要模拟微信内置浏览器,今天教大家用chrome简单模拟.如图设置: F12或者右键审查元素进入开发者模式,点击Emulation,然后点击Network,把Spoof user age ...

  2. python 模拟微信浏览器请求_用chrome在电脑上模拟微信内置浏览器

    先了解安卓微信和Ios微信的UA(User agent:用户代理) 安卓微信UA: mozilla/5.0 (linux; u; android 4.1.2; zh-cn; mi-one plus b ...

  3. 练习:数字时钟(Python 自定义类)

    Python 官网:https://www.python.org/ Free:大咖免费"圣经"教程< python 完全自学教程>,不仅仅是基础那么简单-- My CS ...

  4. Python 自定义类中NameError错误的解决

    Python 自定义类中NameError错误的解决 自定义类之后,python中常常有莫名其妙的NameError提示出错.经尝试后发现,在修改类代码并保存之后,光重新import类是不够的,需要重 ...

  5. python内置对象是什么_Python内置对象类型之数字类型

    Python中有6种内置对象类型 整数.浮点数–Number 字符串–String 列表–List 元组–Tuple 字典–Dictionary 集合–Set 不可变类型:Number.String. ...

  6. boost::python模块实现使用内置 python 数据类型创建 ndarrays 的示例,并提取成员变量的类型和值测试程序

    boost::python模块实现使用内置 python 数据类型创建 ndarrays 的示例,并提取成员变量的类型和值测试程序 实现功能 C++实现代码 实现功能 boost::python模块实 ...

  7. Python自定义类中定义属性的两种方式

    封面图片:<Python程序设计开发宝典>,ISBN:9787302472100,董付国,清华大学出版社 图书详情:https://item.jd.com/12143483.html 京东 ...

  8. python设计自定义函数_我可以为内置Python类型添加自定义方法/属性吗?

    您无法直接将方法添加到原始类型.但是,您可以对类型进行子类化,然后将其替换为内置/全局命名空间,从而实现所需的大部分效果.不幸的是,由文字语法创建的对象将继续属于vanilla类型,并且不会有新的方法 ...

  9. python 自定义类(特殊方法)

    文章目录 1. 对象表示形式 2. 可散列的类 3. 私有属性的利弊 4. `__slots__` 类属性节省空间 5. 覆盖类属性 learn from <流畅的python> from ...

最新文章

  1. maven添加本地jar包依赖
  2. forward 和redirect的区别
  3. [Spring cloud 一步步实现广告系统] 12. 广告索引介绍
  4. Symbian开发平台的搭建之VC++6.0Carbide C++ 2.0
  5. 视频的播放的用例设计点
  6. 微信h5实现分享给朋友url改变_h5微信自定义分享
  7. 51单片机 code关键字
  8. 使用VC开发的一个简单工作日志软件
  9. 水面船舶雷达监视-信天翁雷达监视系统
  10. 二维vector初始化大小方法
  11. U盘启动盘 U盘安装Win10系统图文教程
  12. 常用十大免费建站程序介绍
  13. jetson nano 安装乐视的深度相机orbbec
  14. BUUCTF:[GXYCTF2019]佛系青年
  15. 2007年银行业从业人员资格考试试题及参考答案
  16. 猫眼电影MySQL数据库怎么写_MySQL简要分析猫眼电影TOP100榜
  17. linux 中qq的安装程序,linux下的QQ安装、使用方法
  18. pytorch优化器详解:SGD
  19. Downloader——Linux中的下载利器
  20. 经典开源Windows工具

热门文章

  1. eclipse aop连接点joinpoint方法点不出来_(面试必备)你必须要懂的Spring-Aop
  2. CCF大专委2019年大数据发展趋势预测
  3. 【形式语言与自动机】有限状态机
  4. 领扣-1/167 两数之和 Two Sum MD
  5. API设计原则(觉得太合适,转发做记录)
  6. 性能优化实战案例——助力某移动OA系统
  7. Awesomplete 屌爆了
  8. 加载的图片还会有未来吗?
  9. DataList分页,保存CheckBox控件状态
  10. 15 道超经典大厂 Java 面试题!重中之重