Python 中的元类(关键词:Python/type/元类)

类是 type 类的实例

Python 3 中,用户定义的类是 type 的 1 个实例,type 是 1 个类。

>>> class C:	pass

>>> isinstance(C, type)
True
>>> type(type)
<class 'type'>

元类是 type 类的子类

Python 2 中的新式类和 Python 3 中:
元类是 type 类的 1 个子类。

__new____init__

__new__:用于创建、返回新的 类;

__init__:用于初始化新创建的 类。

class 语句协议

class 语句协议:在 class 语句的末尾,调用 type 对象来创建 类。

class = type(classname, superclasses, attributedict)

type 对象反过来定义了 1 个 __call__ 方法,当调用 type 的时候,自动调用 2 个方法:

type.__new__(typeclass, classname, superclasses, attributedict)
type.__init__(class, classname, superclasses, attributedict)

在类定义中使用元类

Python 3 中:

class Spam(Eggs, metaclass=Meta):	pass

当以这样的方式使用元类的时候,在 class 语句的底部,修改为调用 元类,而不是 type :

class = Meta(classname, superclasses, attributedict)

由于 元类 Meta 是 type 的 1 个子类,所以 type 类的 __call__ 方法把创建、初始化新的类对象的调用委托给元类

Meta.__new__(Meta, classname, superclasses, attributedict)
Meta.__init__(class, classname, superclasses, attributedict)

编写元类

基本元类

class Meta(type):
	def __new__(meta, classname, supers, classdict):
		return type.__new__(meta, classname, supers, classdict)
>>> class MetaOne(type):
	def __new__(meta, classname, supers, classdict):
		print("In MetaOne.new:", classname, supers, classdict, sep='\n...')
		return type.__new__(meta, classname, supers, classdict)
	def __init__(meta, classname, supers, classdict):
		print("In MetaOne.init:", classname, supers, classdict, sep='\n...')
		print('...init class object', list(classdict.keys()))

		
>>> class Spam(Eggs, metaclass=MetaOne):
	data=1
	def meth(self, arg):
		pass

输出:

In MetaOne.new:
...Spam
...(<class '__main__.Eggs'>,)
...{'__qualname__': 'Spam', 'data': 1, '__module__': '__main__', 'meth': <function Spam.meth at 0x0000029C5ED74048>}
In MetaOne.init:
...Spam
...(<class '__main__.Eggs'>,)
...{'__qualname__': 'Spam', 'data': 1, '__module__': '__main__', 'meth': <function Spam.meth at 0x0000029C5ED74048>}
...init class object ['__qualname__', 'data', '__module__', 'meth']

参考文献:

  1. Python 学习手册 - 第 39 章。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
好的,以下是一个简单的爬虫脚本,可以实现你的需求: ```python import requests from bs4 import BeautifulSoup import openpyxl from docx import Document def search_books(keyword): # 发送搜索请求 url = 'http://202.96.31.78/xlsworkbench/publish' data = { 'fileName': keyword, 'type': 'file' } response = requests.post(url, data=data) # 解析搜索结果页面 soup = BeautifulSoup(response.content, 'html.parser') table = soup.find('table', class_='result-table') if not table: return None # 从搜索结果提取书籍信息 books = [] rows = table.find_all('tr') for row in rows[1:]: cols = row.find_all('td') book = { 'title': cols[1].text.strip(), 'author': cols[2].text.strip(), 'publisher': cols[3].text.strip(), 'year': cols[4].text.strip(), 'category': cols[5].text.strip(), 'location': cols[6].text.strip(), } books.append(book) return books def output_excel(books, filename): # 将搜索结果输出为Excel文件 wb = openpyxl.Workbook() ws = wb.active ws.append(['书名', '作者', '出版社', '出版年份', '分类', '馆藏地']) for book in books: ws.append([book['title'], book['author'], book['publisher'], book['year'], book['category'], book['location']]) wb.save(filename) def output_word(books, filename): # 将搜索结果按分类和馆藏地输出为Word文件 doc = Document() categories = set([book['category'] for book in books]) for category in categories: doc.add_heading(category, level=1) category_books = [book for book in books if book['category'] == category] locations = set([book['location'] for book in category_books]) for location in locations: doc.add_heading(location, level=2) location_books = [book for book in category_books if book['location'] == location] for book in location_books: doc.add_paragraph(f"{book['title']} - {book['author']}") doc.save(filename) if __name__ == '__main__': keyword = input('请输入检索关键词:') books = search_books(keyword) if not books: print('未找到相关书籍') exit() output_excel(books, f'{keyword}.xlsx') output_word(books, f'{keyword}.docx') print('搜索结果已输出为文件') ``` 使用说明: 1. 运行脚本后,输入检索关键词,例如 `Python编程`。 2. 脚本会在 http://202.96.31.78/xlsworkbench/publish 网站搜索该关键词,并将搜索结果解析为书籍信息。 3. 将搜索结果以Excel形式输出为 `Python编程.xlsx` 文件,包含书名、作者、出版社、出版年份、分类和馆藏地信息。 4. 将搜索结果按分类和馆藏地输出为Word形式的 `Python编程.docx` 文件。 注意:该脚本仅供学习和参考,使用前请遵守网站的使用规则和法律法规。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值