python 中MethodType方法详解和使用
来源:互联网 发布:linux 查看最后500行 编辑:程序博客网 时间:2024/06/05 02:38
#!/usr/bin/python# -*-coding:utf-8-*-from types import MethodType """文件名 class2.pyMethodType 测试"""# 首先看第一种方式#创建一个方法def set_age(self, arg): self.age = arg #创建一个类 class Student(object): pass#------以上为公共部分
s_one = Student()#给student 创建一个方法 但这里不是在class中创建而是创建了一个链接把外部的set_age 方法用链接知道Student内s_one.set_age = MethodType(set_age,s_one,Student)s_one.set_age(32) #调用实例方法print s_one.age#》》》》结果 32s_two = Student() s_two.set_age(100) #这里来验证下是在类内有方法还是类外有方法。print s_two.age#》》》》结果Traceback (most recent call last):#》》》》 File "class2.py", line 22, in <module>#》》》》 s_two.set_age(100) #这里来验证下是在类内有方法还是类外有方法。#》》》》 AttributeError: 'Student' object has no attribute 'set_age'
看另一种
#直接用类来创建一个方法 不过此时还是用链接的方式在类外的内存中创建Student.set_age = MethodType(set_age,Student)#此时在创建实例的时候外部方法 set_age 也会复制 这些实例和Student类都指向同一个set_age方法new1 = Student()new2 = Student()new1.set_age(99)new2.set_age(98) #第二个会覆盖第一个 print (new1.age,new2.age) #看结果 2个都是98 #》》》》(98, 98)
阅读全文
0 0
- python 中MethodType方法详解和使用
- python MethodType方法详解和使用
- python 使用MethodType绑定方法到类
- python 使用MethodType绑定方法到类
- python中MethodType的使用解析
- python进阶14:实例方法和类方法、types.MethodType()
- python MethodType
- 动态绑定方法 MethodType()
- python中defaultdict方法使用详解
- python双下划线含义、MethodType把函数变为方法以及类继承
- python types模块MethodType的一个例子
- Python应用中使用MongoDB方法步骤详解
- 详解Python的Django框架中Manager方法的使用
- python中的sort方法和sorted使用详解
- Python中pydub使用详解
- Python中模块使用详解
- Python中__new__()方法的使用和实例化
- python wxpython详解和使用
- DataFrame 数据合并方法
- 数组中的排序问题
- MySQL 学习教程(十)【整理】-联合查询
- 2017.11.7总结
- Single Number III
- python 中MethodType方法详解和使用
- #数学期望题目#
- 99乘法表
- Django 下载文件报错UnicodeDecodeError: ‘gbk’ codec can’t decode byte 0xb1 in position 5: illegal multibyte
- Tomcat7.0.42源码研读之BIO(七)
- Hive2.2.0安装
- Unsupported major.minor version 52.0 问题解决
- ConcurrentLinkedQueue的实现原理和源码分析
- L1-003. 个位数统计