@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. c#实现万年历示例分享 万年历农历查询

    cs.cs(类页面) using System;using System.Collections.Generic;using System.Linq;using System.Web; namespa ...

  2. 在命令行下使用perl

    http://blog.sina.com.cn/s/blog_4af3f0d20100g9oz.html aaa@domain.com  2aaa@domain.com 111bbb@home.com ...

  3. 在Update表数据同时将数据备份

    分享一条有意思的SQL语句,也是前两天有个朋友在面试的时候碰到的,他当时没有做出来,回来之后问我, 如何在同一条语句中实现,更新表的时候同时备份更新前的记录数据. --在修改数据前,先要把修改前的数据 ...

  4. sparksql udf的运用----scala及python版(2016年7月17日前完成)

    问:udf在sparksql 里面的作用是什么呢? 答:oracle的存储过程会有用到定义函数,那么现在udf就相当于一个在sparksql用到的函数定义: 第二个问题udf是怎么实现的呢? regi ...

  5. 7. ensemble learning & AdaBoost

    1. ensemble learning 集成学习 集成学习是通过构建并结合多个学习器来完成学习任务,如下图: 集成学习通过将多个学习学习器进行结合,常可以获得比单一学习器更优秀的泛化性能 从理论上来 ...

  6. Spring操作指南-AOP基本示例(基于注解)

  7. openSUSE4.1 安装docker

    安装完Leap后,通过YaST-Software Management安装docker. 安装 docker . yast2-docker. ruby2.1-rubygem-docker-api  . ...

  8. swift 判断字符串长度

    projectName.lengthOfBytes(using: String.Encoding(rawValue: String.Encoding.utf16.rawValue)) > 0

  9. DevExpress 为TextEdit设置水印文字

    设置水印代码: //设置水印值public static void SetWatermark(this TextEdit textEdit, string watermark) { textEdit. ...

  10. 【皇甫】☀Struts_第一节课

    本章讲解内容: DTD是Docunent Type Defintion的缩写,即文档类型定义.DTD用来描述XML文档结构. DOM4J是一个非常优秀的javaXML API,具有性能优异,功能强大和 ...