面对对象之@classmethod、@staticmethod用法
@classmethod用法(修饰的函数,第一个参数cls默认是类名,调用方法:实例对象或类对象.方法)
class C_mthod(object):
name = "f**k"
def __init__(self,name):
self.name = name
@classmethod
def t_mthod(cls):
print("hello world",cls.name) d = C_mthod("F**K")
C_mthod.t_mthod() ————————————————————
hello world f**k
@classmethod调用类静态方法,无法调用类继承方法
分享一个爬虫方法,仅供参考
#!/usr/bin/env python
# -*- coding: utf-8 -*- import random import requests
from lxml import etree class WanfangSpider(object):
@classmethod
def crawl_with_keyword(cls, keyword):
url = 'http://s.wanfangdata.com.cn/Paper.aspx?q=' + keyword
print url
response = requests.get(url, cls.get_headers())
if response.status_code == 200:
return cls.get_info(response.text)
else:
return None @classmethod
def get_headers(cls):
user_agent = [
'Mozilla / 5.0(compatible;MSIE9.0;Windows NT 6.1;Trident / 5.0',
'Mozilla / 4.0(compatible;MSIE6.0;Windows NT 5.1',
'Mozilla / 5.0(compatible;MSIE7.0;Windows NT 5.1',
'Mozilla / 5.0(compatible;MSIE8.0;Windows NT 6.0',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36'
]
headers = {
'User-Agent': random.choice(user_agent)
}
return headers @classmethod
def get_info(cls, content):
tree = etree.HTML(content)
divs = tree.xpath('//*[@class="left-record"]')
result = []
for div in divs:
a_dict = {}
url = div.xpath('div/a[@class="title"]/@href')
title = div.xpath('div/a[@class="title"]')[0].xpath('string(.)')
subtitle = div.xpath('div[@class="record-subtitle"]')[0].xpath('string(.)')
# print url, title, subtitle
if not title:
title = None if url:
url = url[0]
else:
url = None if subtitle:
subtitle = subtitle.strip()
else:
subtitle = None
a_dict['url'] = url
a_dict['title'] = title
a_dict['subtitle'] = subtitle
result.append(a_dict)
return result class It199Spider(object):
@classmethod
def crawl_with_keyword(cls, keyword):
url = 'http://www.199it.com/archives/tag/' + keyword
print url
response = requests.get(url, cls.get_headers())
if response.status_code == 200:
return cls.get_info(response.text)
else:
return None @classmethod
def get_headers(cls):
user_agent = [
'Mozilla / 5.0(compatible;MSIE9.0;Windows NT 6.1;Trident / 5.0',
'Mozilla / 4.0(compatible;MSIE6.0;Windows NT 5.1',
'Mozilla / 5.0(compatible;MSIE7.0;Windows NT 5.1',
'Mozilla / 5.0(compatible;MSIE8.0;Windows NT 6.0',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36'
]
headers = {
'User-Agent': random.choice(user_agent)
}
return headers @classmethod
def get_info(cls, content):
tree = etree.HTML(content)
articles = tree.xpath('//article')
result = []
for article in articles:
a_dict = {} # 提取正文
img_url = article.xpath('div[@class="entry-list-left"]/div/a/img/@src')
title = article.xpath('div[@class="entry-list-right"]/h2/a/text()')
url = article.xpath('div[@class="entry-list-right"]/h2/a/@href')
post_time = article.xpath('div[@class="entry-list-right"]/table/tr/td[2]/text()')
tag = article.xpath('div[@class="entry-list-right"]/table/tr/td[4]/a/text()')
summary = article.xpath('div[@class="entry-list-right"]/p[@class="post-excerpt"]/text()')
print img_url, url, title, post_time, tag, summary # 构造字典
a_dict['img_url'] = img_url[0] if img_url else None
a_dict['title'] = title[0] if title else None
a_dict['url'] = url[0] if url else None
a_dict['post_time'] = post_time[0] if post_time else None
a_dict['tag'] = tag[0] if tag else None
a_dict['summary'] = summary[0] if summary else None
result.append(a_dict)
return result if len(result) < 10 else result[0: 10]
classmethod类方法使用
@staticmethod(不需要表示自身对象的self和自身类的cls参数,就跟使用函数一样。调用方法:实例对象或类对象.方法 )
class A(object):
bar = 1
def foo(self):
print('foo') @staticmethod
def static_foo():
print('static_foo')
print(A.bar) @classmethod
def class_foo(cls):
print('class_foo')
print(cls.bar)
cls().foo() A.static_foo()
A.class_foo() ——————————————————————
static_foo
1
class_foo
1
foo
面对对象之@classmethod、@staticmethod用法的更多相关文章
- python:类与对象命名空间、面对对象的组合用法
1,类里可以定义两种属性: #静态属性 #静态属性就是直接在类中定义的变量 #动态属性 #动态属性就是定义在类中的方法 class Course: language = ['Chinese']#静态属 ...
- 16、python面对对象之类和继承
前言:本文主要介绍python面对对象中的类和继承,包括类方法.静态方法.只读属性.继承等. 一.类方法 1.类方法定义 使用装饰器@classmethod装饰,且第一个参数必须是当前类对象,该参数名 ...
- python面对对象(不全解)
面对对象:以人类为例,人类通用功能:吃喝拉撒,就可以封装成一个类,不同功能:嫖赌毒,就是对象的不同功能.继承,多态… 上码 class Person(object): def __init__(sel ...
- Python面对对象相关知识总结
很有一段时间没使用python了,前两天研究微信公众号使用了下python的django服务,感觉好多知识都遗忘了,毕竟之前没有深入的实践,长期不使用就忘得快.本博的主要目的就是对Python中我认为 ...
- Python - 面对对象(进阶)
目录 Python - 面对对象(进阶) 类的成员 一. 字段 二. 方法 三. 属性 类的修饰符 类的特殊成员 Python - 面对对象(进阶) 类的成员 一. 字段 字段包括:普通字段和静态字段 ...
- 小学生绞尽脑汁也学不会的python(面对对象-----成员)
小学生绞尽脑汁也学不会的python(面对对象-----成员) 成员 class Person: def __init__(self, name, num, gender, birthday): # ...
- python面对对象编程----2:__init__
面对对象编程估计我们最早接触到的就是__init__了,也就是实例的初始化处理过程: 1:来看看最基础的__init__ class Card(object): #抽象类Card,并不用于实例化 de ...
- Python - 面对对象(其他相关,异常处理,反射,单例模式,等..)
目录 Python - 面对对象(其他相关,异常处理,反射,等..) 一.isinstance(obj, cls) 二.issubclass(sub, super) 三.异常处理 1. 异常处理 2. ...
- 初识面向对象(钻石继承,super,多态,封装,method,property,classmethod,staticmethod)
组合 什么有什么的关系 一个类的对象作为另一个类的对象继承 子类可以使用父类中的名字(静态属性 方法)抽象类和接口类 只能不继承,不能被实例化 子类必须实现父类中的同名方法———规范代码 metacl ...
随机推荐
- 去除select的样式
select::-ms-expand { display: none } .info-select { width: 88px; height: 25px; border: none; outline ...
- win7 WindowsImageBackup 无法识别
控制面板\所有控制面板项\备份和还原
- Java读写资源文件类Properties
Java中读写资源文件最重要的类是Properties 1) 资源文件要求如下: 1.properties文件是一个文本文件 2.properties文件的语法有两种,一种是注释,一种属性配置. 注 ...
- SQL学习整理_1
数据库是保存表和其他相关SQL结构的容器. 列是存储在表中的一块同类型数据. 行是一组能够描述某个事物的列的集合. SQL不区分大小写,但建议命令采用大写,表名采用小写,便于读写. 建立数据库 CRE ...
- HTML5web存储之localStorage
localStorage与cookie的作用类似,只能存储字符串,以键值对的方式进行存储:与cookie不同的是,可以存储更多的数据. localStorage用于持久化的本地存储. var skey ...
- vm网络设置
设置NET模式 cat /etc/sysconfig/network-scripts/ifcfg-eth0 DEVICE="eth0" BOOTPROTO="stati ...
- 代码回滚:git reset、git checkout和git revert区别和联系
git reset.git checkout和git revert是你的Git工具箱中最有用的一些命令.它们都用来撤销代码仓库中的某些更改,而前两个命令不仅可以作用于提交,还可以作用于特定文件. 因为 ...
- Leetcode: Sequence Reconstruction
Check whether the original sequence org can be uniquely reconstructed from the sequences in seqs. Th ...
- js执行环境的深入理解
第一个例子中 :之所以每个函数都返回不同的值的原因 有2点 (简写如下文) 就是[SCOPE]内部属性,函数可能拥有相同的父作用域时,多个函数引用同一个[SCOPE]属性,所以return i的值还是 ...
- IP釋放、清除、以及刷新DNS
Windows 10 於桌面按住 Windows + X 按鍵. 選擇 Command Prompt (以管理員執行). 在彈跳視窗中輸入 ipconfig /release. 等待數秒回報此 IP ...