[Python3 填坑] 018 组装类的几个例子
2024-09-03 23:23:54
1. print( 坑的信息 )
- 挖坑时间:2019/04/07
- 明细
坑的编码 | 内容 |
---|---|
Py024-2 | MethodType 举例 |
Py024-3 | type 举例 |
Py024-4 | MetaClass 举例 |
2. 开始填坑
2.1 MetaClass 举例
from types import MethodType
class A():
pass
def say(self):
print("this is say()")
a = A()
a.say = MethodType(say, A)
a.say()
>>>
this is say()
2.2 type 举例
# 1. 定义类应该具有的成员函数
def say(self):
print("this is say()")
def eat(self):
print("this is eat()")
# 2. 用 type 来创建一个类
A = type( "AName", (object, ), {"class_say":say, "class_eat":eat})
# 3. 像正常访问一样使用类
a = A()
a.class_say()
a.class_eat()
>>>
this is say()
this is eat()
2.3 MetaClass 举例
# 元类写法是固定的,必须继承自 type
# 元类一般命名以 MetaClass 结尾
class ExampleMetaClass(type):
def __new__(cls, region, gender, attrs):
print("this is MetaClass")
attrs['id_num'] = '9527'
attrs['age'] = "18"
return type.__new__(cls, region, gender, attrs)
# 元类定义完就可以使用
class Person(object, metaclass=ExampleMetaClass):
pass
york = Person()
print(york.id_num)
>>>
this is MetaClass
9527
最新文章
- JavaScript框架设计(四) 字符串选择器(选择器模块结束)
- FineUI Grid控件高度自适应
- JS根据登录的城市不同调用不同的内容
- DEDECMS之三 首页、列表页怎么调用文章内容
- 第一次正式小用Redis存储
- BIO,NIO,AIO的理解
- PetaPOCO 一对多 多对一 多对多
- mkfs.xfs命令没找到
- linux下源码安装软件
- C#word(2007)操作类--新建文档、添加页眉页脚、设置格式、添加文本和超链接、添加图片、表格处理、文档格式转化
- logstash 使用grok正则解析日志
- IIS ASP.NET 版本转换批处理代码
- python py2与py3的编码问题
- Hibernate——配置并访问数据库
- 记一次zabbix排错(数据库安装在其它服务器上)
- blinker库
- MinGW 编译 libaom 1.0.0 注意事项
- Guitar Pro 添加装饰音
- Fiddler系列教程1:初识Http协议抓包工具
- MEF程序设计指南