@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用法的更多相关文章

  1. python:类与对象命名空间、面对对象的组合用法

    1,类里可以定义两种属性: #静态属性 #静态属性就是直接在类中定义的变量 #动态属性 #动态属性就是定义在类中的方法 class Course: language = ['Chinese']#静态属 ...

  2. 16、python面对对象之类和继承

    前言:本文主要介绍python面对对象中的类和继承,包括类方法.静态方法.只读属性.继承等. 一.类方法 1.类方法定义 使用装饰器@classmethod装饰,且第一个参数必须是当前类对象,该参数名 ...

  3. python面对对象(不全解)

    面对对象:以人类为例,人类通用功能:吃喝拉撒,就可以封装成一个类,不同功能:嫖赌毒,就是对象的不同功能.继承,多态… 上码 class Person(object): def __init__(sel ...

  4. Python面对对象相关知识总结

    很有一段时间没使用python了,前两天研究微信公众号使用了下python的django服务,感觉好多知识都遗忘了,毕竟之前没有深入的实践,长期不使用就忘得快.本博的主要目的就是对Python中我认为 ...

  5. Python - 面对对象(进阶)

    目录 Python - 面对对象(进阶) 类的成员 一. 字段 二. 方法 三. 属性 类的修饰符 类的特殊成员 Python - 面对对象(进阶) 类的成员 一. 字段 字段包括:普通字段和静态字段 ...

  6. 小学生绞尽脑汁也学不会的python(面对对象-----成员)

    小学生绞尽脑汁也学不会的python(面对对象-----成员) 成员 class Person: def __init__(self, name, num, gender, birthday): # ...

  7. python面对对象编程----2:__init__

    面对对象编程估计我们最早接触到的就是__init__了,也就是实例的初始化处理过程: 1:来看看最基础的__init__ class Card(object): #抽象类Card,并不用于实例化 de ...

  8. Python - 面对对象(其他相关,异常处理,反射,单例模式,等..)

    目录 Python - 面对对象(其他相关,异常处理,反射,等..) 一.isinstance(obj, cls) 二.issubclass(sub, super) 三.异常处理 1. 异常处理 2. ...

  9. 初识面向对象(钻石继承,super,多态,封装,method,property,classmethod,staticmethod)

    组合 什么有什么的关系 一个类的对象作为另一个类的对象继承 子类可以使用父类中的名字(静态属性 方法)抽象类和接口类 只能不继承,不能被实例化 子类必须实现父类中的同名方法———规范代码 metacl ...

随机推荐

  1. H264编码原理以及I帧、B和P帧详解

    H264是新一代的编码标准,以高压缩高质量和支持多种网络的流媒体传输著称,在编码方面,我理解的他的理论依据是:参照一段时间内图像的统计结果表明,在相邻几幅图像画面中,一般有差别的像素只有10%以内的点 ...

  2. .net DropDownList静态联动

    1.前台 <span id="spnClient" style="margin-left: 30px; margin-top: 10px"> < ...

  3. css3图片翻转

    <!DOCTYPE> <html lang="en"> <head> <meta http-equiv="Content-Typ ...

  4. nginx 配置优化(简单)

    配置文件     正常运行的必备配置:         1.user username [groupname]:(推荐nginx)         以那个用户身份运行,以在configure指定的用户 ...

  5. glob模块

    Python模块(glob) 主要是用来在匹配文件,相当于在shell中用通配符匹配.  参考:  http://python.usyiyi.cn/python_278/library/glob.ht ...

  6. python之面向对象编程

    1.面向对象介绍: 世界万物,皆可分类 世界万物,皆为对象 只要是对象,就肯定属于某种类 只要是对象,就肯定有属性 2. 面向对象的几个特性: class类: 一个类即对一类拥有相同属性的对象的抽象, ...

  7. iOS获取当前AppStore版本号与更新

    - (void)checkUpdateWithAppID:(NSString *)appID success:(void (^)(NSDictionary *resultDic , BOOL isNe ...

  8. DataAnnotations里DisplayAttribute和 ValidationAttribute 如何从资源文件读取信息,显示多语言

    这个是我们常见的AccountModel代码 public class ChangePasswordModel { [Required] [DataType(DataType.Password)] [ ...

  9. SQLServer针对排名函数ROWNUMBER()、RANK()、DENSE_RANK()、NTILE的研究!~

    相信大家在软件工程中经常会遇到对某些数据进行排名的问题,尤其是对于电子商务的HR来说“大手笔”是非常具有潜在价值的!~至于都有哪些价值这个超出本文的范畴不予进行说明,但是不得不说的是每一个精明的HR以 ...

  10. The connection to adb is down,and a server error has occured.解决办法---------------------亲测有效

    认真读error: 办法一: 点击项目右键->Android tools ->Fix Project Properties,检查项目属性 办法二: 设备管理器,查看是否存在adb进程 如果 ...