面对对象之@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 ...
随机推荐
- FDCT变换 公式法
// 对亮度信号进行FDCT变换// @param data 亮度信号的存储数组void CompressEncode::standardFDCT(BYTE data[MATRIXSIZE] ...
- ios上position:fixed失效问题
手机端上的猫腻真是多啊~~~ 此起彼伏! 最近又遇到了 固定定位的底部导航在ios上被弹出去 此时内心1w+个草泥马奔过~~~~~~~~ 直接上解决方案: <div class="ma ...
- Sping
- Android开发环境配置
由于公司项目需要,最近转做Android开发,这里我来介绍一下Android开发环境的配置过程. 首先,需要下载所需要的软件工具,如下所示: 1.Java:开发基础环境,JDK和JRE这两个都要下载的 ...
- ASP.NET MVC 4 Attribute特性
[AcceptVerbs(-)] To specify HTTP verbs an action method will respond to. 要指定HTTP动词的将响应的一个操作方法. [Acti ...
- 如何理解泛型中的new()约束
一:为什么需要New约束 假设有这样一个需求,它需要在定义一个泛型类时同时实例化T对象.有网友说了:"这还不简单,我立刻给你写一个",刷刷刷,得到以下的例子. public cla ...
- 开启JMX功能,使JVisvualVM能够连接JVM
-Dcom.sun.management.jmxremote.port=1099 -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.manageme ...
- MyEclipse 及Tomcate 安装 配置
使用的工具为myeclipse-pro-2014-GA-offline-installer-windows(需安装).apache-tomcat-6.0.37.jdk1.6.0.14. 1.MyEcl ...
- CentOS 7中防火墙 firewall-cmd命令
在 CentOS 7 iptable 防火墙已经被 firewall替代 1.暂时开放FTP服务 firewall-cmd --add-service=ftp 2.永久开放FTP服务 firewall ...
- Css深入理解之浮动_慕课网课程笔记
前言 这篇是在慕课网上跟着张鑫旭重走CSS之路的第三篇学习笔记了,主要是学习float属性,闲话少说,下面进入正文. float的历史 要想了解一个东西,我们还是需要从本质去了解它,那么我们就需要问一 ...