静态方法

类方法

属性方法

通过@staticmethod装饰器即可把其装饰的方法变为一个静态方法,什么是静态方法呢?其实不难理解,普通的方法,可以在实例化后直接调用,并且在方法里可以通过self.调用实例变量或类变量,但静态方法是不可以访问实例变量或类变量的,一个不能访问实例变量和类变量的方法,其实相当于跟类本身已经没什么关系了,它与类唯一的关联就是需要通过类名来调用这个方法

类方法通过@classmethod装饰器实现,类方法和普通方法的区别是, 类方法只能访问类变量,不能访问实例变量

属性方法的作用就是通过@property把一个方法变成一个静态属性

#-*- encoding:utf8 -*-
#Wind clear raise class Dog(): member = 0 def __init__(self, name):
self.name = name
def walk(self):
print("walk function") @staticmethod # 无法通过self访问属性、方法
def talk(self):
#self.walk()
print("Talk now is: ", self.name) class Animal(object):
name = "类变量"
def __init__(self, name):
self.name = name @classmethod # 设置方法只能访问类变量,无法访问类属性
def talk(self):
print("The Animal talk:", self.name) class Person(object):
def __init__(self, name):
self.name = name
@property # 将一个方法设置为属性
def eat(self): # 无法通过Person.eat()调用
print(self.name, "is eating")
return "hel" d = Dog("DD")
#d.talk("aaaaa") #AttributeError: 'str' object has no attribute 'name'
d.talk(d) a = Animal("Dark")
a.talk() p = Person("Fengqingyang")
s = p.eat
print("return [%s]" % s)

Talk now is: DD
The Animal talk: 类变量
Fengqingyang is eating
return [hel]

二、特殊属性及成员

__doc__ __class__ __module__ __dict__

class Dog():
"""Dog doc content"""
###
#-*- encoding:utf8 -*-
#Wind clear raise from 类的特殊属性方法_2 import Dog class Foo(object):
"""doc内容"""
def __init__(self, name):
self.name = name def __call__(self, *args, **kwargs):
print("__call__:", args, kwargs) f = Foo("Wind")
print(Foo.__doc__)
print(f.__class__, f.__module__)
d = Dog()
print(d.__module__, d.__class__)
print(d.__doc__)
f("hello", name="test")
#Foo("")("call", age=333)
print(Foo.__dict__) # 类的所有属性成员
print(f.__dict__) # 实例的所有属性成员
f.name = "dict测试"
print(Foo.__dict__) # 结果内容不变
print(f.__dict__) # 实例内容name变更
“”“
/Library/Frameworks/Python.framework/Versions/3.5/bin/python3.5 /data/youngboy/youngboy/study/day07/类的特殊属性方法.py
doc内容
<class '__main__.Foo'> __main__
类的特殊属性方法_2 <class '类的特殊属性方法_2.Dog'>
Dog doc content
__call__: ('hello',) {'name': 'test'}
{'__init__': <function Foo.__init__ at 0x1021df378>, '__module__': '__main__', '__call__': <function Foo.__call__ at 0x1021df400>, '__dict__': <attribute '__dict__' of 'Foo' objects>, '__doc__': 'doc内容', '__weakref__': <attribute '__weakref__' of 'Foo' objects>}
{'name': 'Wind'}
{'__init__': <function Foo.__init__ at 0x1021df378>, '__module__': '__main__', '__call__': <function Foo.__call__ at 0x1021df400>, '__dict__': <attribute '__dict__' of 'Foo' objects>, '__doc__': 'doc内容', '__weakref__': <attribute '__weakref__' of 'Foo' objects>}
{'name': 'dict测试'} Process finished with exit code 0 ”“”

2、__str__、__getitem__、__setitem__  __delitem__

class Dog():
"""Dog doc content"""
def __init__(self, name):
self.name = name def __str__(self): ##print(d)
return "Wind"
def test(self):
pass
def __getitem__(self, item): # 调用时触发
print("getitem: ", item)
def __setitem__(self, key, value):
print("setitem: ", key, value) # 设置时触发
def __delitem__(self, key): # 删除时触发
print("del:", key) d = Dog("Dog")
print(d) result = d["k"] # 触发 __getitem__
d["k"] = "setkey" # 触发 __setitem
del d["k"] # 触发__delitem__
"""

Wind
getitem: k
setitem: k setkey
del: k

"""

类的另类定义:

def func(self):
print("hello Wind ", self.name, self.age) def __init__(self,name, age):
self.name = name
self.age = age # 利用逼格定义类, 同时也说明python一切皆对象
Foo = type('Foo2', (object,), {'talk': func, '__init__': __init__})
# 类名 type(object_or_name, bases, dict) f = Foo("Wind", 33)
f.talk() print(type(f))
print(type(Foo))

hello Wind Wind 33
<class '__main__.Foo2'>
<class 'type'>

类的生成 调用 顺序依次是 __new__ --> __call__ --> __init__

 class Foo(object):
def __init__(self):
print("init") def __call__(self, *args, **kwargs):
print("hello call") def __new__(cls, *args, **kwargs):
print("hello new")
return object.__new__(cls) # 去继承父类的__new__方法
# 类似 F.__init__(self) f = Foo()

hello new
init

__new__  在实例化之前干点什么事

class Foo(object):
def __init__(self, name):
self.name = name
print("init") def __call__(self, *args, **kwargs):
print("hello call") def __new__(cls, *args, **kwargs):
print("hello new")
# return object.__new__(cls) # 去继承父类的__new__方法
# 类似 F.__init__(self) f = Foo()
print(type(f)) 程序结果 f 没有真正的创建,so,在init之前运行了new
<class 'NoneType'>

反射

class Foo(object):
def walk(self):
print("walk") def talk(msg=""):
print("hello talk") s = input(">>").strip()
obj =Foo() if hasattr(obj, s):
v = getattr(obj, s)
v() else:
setattr(obj, s, talk)
v = getattr(obj, s)
v() print(dir(obj)) '''
>>input_str
hello talk
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'input_str', 'walk'] '''

异常:

 a = []
s = {}
s[1] = "hello" try:
# a[3]
# b
# c = 1
# s[2]
open("aaa")
except (IndexError, KeyError) as e: # 多个异常写在一起
print("异常 ", e)
except NameError as e: # 单个异常
print("异常", e)
except Exception as e:
print("各种异常:", e)
else: # 无异常
print("无异常")
finally: # 最终
print("无论有无异常、表示感谢") class MyException(BaseException): # 自定义异常
def __init__(self, msg):
self.msg = msg # 重载父类 __str__, 父类默认直接 return self.msg
# def __str__(self):
# print("str....") # 先输出 str... 然后输出msg
# return self.msg try:
raise MyException("我的异常") # 直接抛出异常
except MyException as e: #
print("自定义: ", e)

Python学习记录之(五)-----类进阶篇的更多相关文章

  1. python学习第十六天 --继承进阶篇

    这一章节主要讲解面向对象高级编程->继承进阶篇,包括类多继承介绍和继承经典类和新式类属性的查找顺序不同之处. 多继承 上一章节我们讲到继承,子类继承父类,可以拥有父类的属性和方法,也可以进行扩展 ...

  2. python 学习笔记十一 SQLALchemy ORM(进阶篇)

    SqlAlchemy ORM SQLAlchemy是Python编程语言下的一款ORM框架,该框架建立在数据库API之上,使用关系对象映射进行数据库操作,简言之便是:将对象转换成SQL,然后使用数据A ...

  3. python学习之路-5 基础进阶篇

    本篇涉及内容 双层装饰器字符串格式化 双层装饰器 装饰器基础请点我 有时候一个功能需要有2次认证的时候就需要用到双层装饰器了,下面我们来通过一个案例详细介绍一下双层装饰器: 执行顺序:自上而下 解释顺 ...

  4. python学习笔记七 初识socket(进阶篇)

    socket socket通常也称作"套接字",用于描述IP地址和端口,是一个通信链的句柄,应用程序通常通过"套接字"向网络发出请求或者应答网络请求. sock ...

  5. python学习记录(五)

    20180829--https://www.cnblogs.com/fnng/archive/2013/04/20/3032563.html 字典 字典的使用 现实中的字段及在Python中的字段都进 ...

  6. 图解Python 【第六篇】:面向对象-类-进阶篇

    由于类的内容比较多,分为类-初级基础篇和类-进阶篇 本节内容一览图: 一.类成员修饰符 每一个类的成员都有两种形式: 公有成员,在任何地方都能访问 私有成员,只能在类的内部才能访问 1.1.私有成员和 ...

  7. Python之路,Day15 - Django适当进阶篇

    Python之路,Day15 - Django适当进阶篇   本节内容 学员管理系统练习 Django ORM操作进阶 用户认证 Django练习小项目:学员管理系统设计开发 带着项目需求学习是最有趣 ...

  8. Python学习记录day5

    title: Python学习记录day5 tags: python author: Chinge Yang date: 2016-11-26 --- 1.多层装饰器 多层装饰器的原理是,装饰器装饰函 ...

  9. python学习笔记(五岁以下儿童)深深浅浅的副本复印件,文件和文件夹

    python学习笔记(五岁以下儿童) 深拷贝-浅拷贝 浅拷贝就是对引用的拷贝(仅仅拷贝父对象) 深拷贝就是对对象的资源拷贝 普通的复制,仅仅是添加了一个指向同一个地址空间的"标签" ...

随机推荐

  1. icon工具类

    using System; using System.Drawing; using System.Collections; using System.ComponentModel; using Sys ...

  2. 使用Bootstrap Popover实现一个弹框上三角形的代码记录

          $(function () {        var options = {          trigger: 'manual',          content: function ...

  3. cd 命令

    [root@localhost ~]# cd # 进入当前用户的家目录 [root@localhost ~]# cd ~ # 进入当前用户的家目录 [root@localhost ~]# cd /da ...

  4. OC侧滑删除

    做侧滑的时候发现一个问题,当一个UITableView的cell有的有侧滑,有的没有,当用editActionsForRowAtIndexPath方法的时候发现有点问题,查看了下api,需要用到can ...

  5. 初试GH-OST(转)

    最近老板让做一个gh-ost和pt-osc 的对比测试,本文将对两者做对比. 一.原理和所用说明   PT-OSC GH-OST 原理 1.创建一个和要执行 alter 操作的表一样的新的空表结构(是 ...

  6. 013-程序性能分析之thread dump和heap dump

    一.dump基本概念 主要用于故障定位(尤其是out of memory)和性能分析.主要记录了JVM运行期间的内存占用.线程执行等情况,这就是常说的dump文件.常用的有heap dump和thre ...

  7. winform里直接使用WCF,不需要单独的WCF项目

    https://www.cnblogs.com/fengwenit/p/4249446.html 依照此法建立即可, 但是vs生成的配置有误,正确配置如下 <?xml version=" ...

  8. cookie存值 后取值是string string字符串转对象

    实现方法 // 得到 对象 格式或 json 格式的一个字符串 var str = '{"name":"张根硕","age":"1 ...

  9. 通过wui登陆 sap 页面对数据进行高级 搜索

    1: 登陆QGL系统. 在 T-CODE搜索框输入wui 会跳到搜索的web页面,进行搜索. 或者浏览器输入: https://ldciqgl.wdf.sap.corp:44300/sap(bD1lb ...

  10. abap特性

    1:实例成员是属于某一个对象的,静态成员属于整个类. 2:abap类中,可以定义三种不同类型的成员,分布是属性(如data),方法(method),事件(event). 3: abap中定义静态属性的 ...