静态方法

类方法

属性方法

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

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

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

  1. #-*- encoding:utf8 -*-
  2. #Wind clear raise
  3.  
  4. class Dog():
  5.  
  6. member = 0
  7.  
  8. def __init__(self, name):
  9. self.name = name
  10. def walk(self):
  11. print("walk function")
  12.  
  13. @staticmethod # 无法通过self访问属性、方法
  14. def talk(self):
  15. #self.walk()
  16. print("Talk now is: ", self.name)
  17.  
  18. class Animal(object):
  19. name = "类变量"
  20. def __init__(self, name):
  21. self.name = name
  22.  
  23. @classmethod # 设置方法只能访问类变量,无法访问类属性
  24. def talk(self):
  25. print("The Animal talk:", self.name)
  26.  
  27. class Person(object):
  28. def __init__(self, name):
  29. self.name = name
  30. @property # 将一个方法设置为属性
  31. def eat(self): # 无法通过Person.eat()调用
  32. print(self.name, "is eating")
  33. return "hel"
  34.  
  35. d = Dog("DD")
  36. #d.talk("aaaaa") #AttributeError: 'str' object has no attribute 'name'
  37. d.talk(d)
  38.  
  39. a = Animal("Dark")
  40. a.talk()
  41.  
  42. p = Person("Fengqingyang")
  43. s = p.eat
  44. print("return [%s]" % s)

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

二、特殊属性及成员

__doc__ __class__ __module__ __dict__

  1. class Dog():
  2. """Dog doc content"""
  3. ###
  4. #-*- encoding:utf8 -*-
  5. #Wind clear raise
  6.  
  7. from 类的特殊属性方法_2 import Dog
  8.  
  9. class Foo(object):
  10. """doc内容"""
  11. def __init__(self, name):
  12. self.name = name
  13.  
  14. def __call__(self, *args, **kwargs):
  15. print("__call__:", args, kwargs)
  16.  
  17. f = Foo("Wind")
  18. print(Foo.__doc__)
  19. print(f.__class__, f.__module__)
  20. d = Dog()
  21. print(d.__module__, d.__class__)
  22. print(d.__doc__)
  23. f("hello", name="test")
  24. #Foo("")("call", age=333)
  25. print(Foo.__dict__) # 类的所有属性成员
  26. print(f.__dict__) # 实例的所有属性成员
  27. f.name = "dict测试"
  28. print(Foo.__dict__) # 结果内容不变
  29. print(f.__dict__) # 实例内容name变更
  30. “”“
  31. /Library/Frameworks/Python.framework/Versions/3.5/bin/python3.5 /data/youngboy/youngboy/study/day07/类的特殊属性方法.py
  32. doc内容
  33. <class '__main__.Foo'> __main__
  34. 类的特殊属性方法_2 <class '类的特殊属性方法_2.Dog'>
  35. Dog doc content
  36. __call__: ('hello',) {'name': 'test'}
  37. {'__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>}
  38. {'name': 'Wind'}
  39. {'__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>}
  40. {'name': 'dict测试'}
  41.  
  42. Process finished with exit code 0
  43.  
  44. ”“”

2、__str__、__getitem__、__setitem__  __delitem__

  1. class Dog():
  2. """Dog doc content"""
  3. def __init__(self, name):
  4. self.name = name
  5.  
  6. def __str__(self): ##print(d)
  7. return "Wind"
  8. def test(self):
  9. pass
  10. def __getitem__(self, item): # 调用时触发
  11. print("getitem: ", item)
  12. def __setitem__(self, key, value):
  13. print("setitem: ", key, value) # 设置时触发
  14. def __delitem__(self, key): # 删除时触发
  15. print("del:", key)
  16.  
  17. d = Dog("Dog")
  18. print(d)
  19.  
  20. result = d["k"] # 触发 __getitem__
  21. d["k"] = "setkey" # 触发 __setitem
  22. del d["k"] # 触发__delitem__
    """

Wind
getitem: k
setitem: k setkey
del: k

  1. """

类的另类定义:

  1. def func(self):
  2. print("hello Wind ", self.name, self.age)
  3.  
  4. def __init__(self,name, age):
  5. self.name = name
  6. self.age = age
  7.  
  8. # 利用逼格定义类, 同时也说明python一切皆对象
  9. Foo = type('Foo2', (object,), {'talk': func, '__init__': __init__})
  10. # 类名 type(object_or_name, bases, dict)
  11.  
  12. f = Foo("Wind", 33)
  13. f.talk()
  14.  
  15. print(type(f))
  16. print(type(Foo))

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

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

  1. class Foo(object):
  2. def __init__(self):
  3. print("init")
  4.  
  5. def __call__(self, *args, **kwargs):
  6. print("hello call")
  7.  
  8. def __new__(cls, *args, **kwargs):
  9. print("hello new")
  10. return object.__new__(cls) # 去继承父类的__new__方法
  11. # 类似 F.__init__(self)
  12.  
  13. f = Foo()

hello new
init

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

  1. class Foo(object):
  2. def __init__(self, name):
  3. self.name = name
  4. print("init")
  5.  
  6. def __call__(self, *args, **kwargs):
  7. print("hello call")
  8.  
  9. def __new__(cls, *args, **kwargs):
  10. print("hello new")
  11. # return object.__new__(cls) # 去继承父类的__new__方法
  12. # 类似 F.__init__(self)
  13.  
  14. f = Foo()
  15. print(type(f))
  16.  
  17. 程序结果 f 没有真正的创建,so,在init之前运行了new
  18. <class 'NoneType'>

反射

  1. class Foo(object):
  2. def walk(self):
  3. print("walk")
  4.  
  5. def talk(msg=""):
  6. print("hello talk")
  7.  
  8. s = input(">>").strip()
  9. obj =Foo()
  10.  
  11. if hasattr(obj, s):
  12. v = getattr(obj, s)
  13. v()
  14.  
  15. else:
  16. setattr(obj, s, talk)
  17. v = getattr(obj, s)
  18. v()
  19.  
  20. print(dir(obj))
  21.  
  22. '''
  23. >>input_str
  24. hello talk
  25. ['__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']
  26.  
  27. '''

异常:

  1. a = []
  2. s = {}
  3. s[1] = "hello"
  4.  
  5. try:
  6. # a[3]
  7. # b
  8. # c = 1
  9. # s[2]
  10. open("aaa")
  11. except (IndexError, KeyError) as e: # 多个异常写在一起
  12. print("异常 ", e)
  13. except NameError as e: # 单个异常
  14. print("异常", e)
  15. except Exception as e:
  16. print("各种异常:", e)
  17. else: # 无异常
  18. print("无异常")
  19. finally: # 最终
  20. print("无论有无异常、表示感谢")
  21.  
  22. class MyException(BaseException): # 自定义异常
  23. def __init__(self, msg):
  24. self.msg = msg
  25.  
  26. # 重载父类 __str__, 父类默认直接 return self.msg
  27. # def __str__(self):
  28. # print("str....") # 先输出 str... 然后输出msg
  29. # return self.msg
  30.  
  31. try:
  32. raise MyException("我的异常") # 直接抛出异常
  33. except MyException as e: #
  34. 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. 获取文件后缀名(zip,rar等)

    var filename = file.name; var index1 = filename.lastIndexOf("."); var index2 = filename.le ...

  2. 洛谷P4052 [JSOI2007]文本生成器 AC自动机+dp

    正解:AC自动机+dp 解题报告: 传送门! 感觉AC自动机套dp的题还挺套路的,,, 一般就先跑遍AC自动机,然后就用dp dp的状态一般都是f[i][j]:有i个字符,是ac自动机上的第j个节点, ...

  3. 【python基础】sys

    sys模块 参考: https://blog.csdn.net/qq_38526635/article/details/81739321 http://www.cnblogs.com/cherishr ...

  4. VB改写C#

    1.VB的Val()函数 先从程序集中引入Microsoft.VisualBasic命名空间.不过,即便是引入了Microsoft.VisualBasic命名空间,还是不能直接使用像Val()这样的函 ...

  5. es6原型的继承

    class Parent { name = 'liangcheng'; } const parent = new Parent(); console.log(parent); // 类继承某实例对象属 ...

  6. FlashFXP+FileZillaServer

    从远程站点里拷贝文件到本地时,如果文件太大,通常会非常耗时,再加上若需要拨VPN,网络上的任何波动都会造成传输文件失败从头来过. 运用FlashFXP和FileZillaServer这两个工具,它拥有 ...

  7. rem : web app适配的秘密武器

    css html { font-size: calc(100vw / 3.75) } jsdocument.documentElement.style.fontSize = $(document.do ...

  8. what's the 爬虫之基本原理

    what's the 爬虫? 了解爬虫之前,我们首先要知道什么是互联网 1.什么是互联网? 互联网是由网络设备(网线,路由器,交换机,防火墙等等)和一台台计算机连接而成,总体上像一张网一样. 2.互联 ...

  9. java poi生成excel(个人例子js-jsp-java)

    js代码: function exportRepQudl(){ if(confirm("导出输出页面内容?")){ var id = $("input[name='id' ...

  10. Git的安装和配置用户名和密码

    在Windows中进行安装.访问https://git-scm.com/,点击Downloads for Windows,我下载的是Git-2.16.2-64-bit.exe.都按照默认选项即可,其中 ...