classmethod,staticmethod,反射,魔法方法,单例模式
classmethod
classmethod是一个装饰器,可以装饰给类内部的方法,使该方法绑定给类来使用
- 对象绑定方法特殊之处:由对象来调用,会把对象当作第一个参数传给该方法
- 类绑定方法特殊之处:由类来调用,会把类当作第一个参数传给该方法
class People:
def __init__(self, name, age):
self.name = name
self.age = age
@classmethod
def tell_info(cls):
print(cls)
print('此处是类方法。。。')
People.tell_info()
'''
<class '__main__.People'>
此处是类方法。。。
'''
小练习:
# settings.py
'''
USER = 'tank'
PWD = '123'
'''
import settings
class Teacher:
def __init__(self, user, pwd):
self.user = user
self.pwd = pwd
# 显示主页
def index(self):
if self.user == 'tank' and self.pwd == '123':
print('验证成功,显示主页')
@classmethod
def login_auth(cls):
obj = cls(settings.USER, settings.PWD)
return obj
obj = Teacher.login_auth()
obj.index()
staticmethod
staticmethod是一个装饰器,可以装饰给类内部的方法,使得该方法既不绑定类,也不绑定对象
import settings
import uuid
import hashlib
class Teacher:
def __init__(self, user, pwd):
self.user = user
self.pwd = pwd
# 显示主页
def index(self):
if self.user == 'tank' and self.pwd == '123':
print('验证成功,显示主页')
@classmethod
def login_auth(cls):
obj = cls(settings.USER, settings.PWD)
return obj
@staticmethod
def create_id():
uuid_obj = uuid.uuid4()
md5 = hashlib.md5()
md5.update(str(uuid_obj).encode('utf-8'))
return md5.hexdigest()
print(Teacher.create_id())
t1 = Teacher('tank', 123)
print(t1.create_id())
instance
python内置函数,可以传入两个参数,用于判断参数1是否是参数2的一个实例。
判断一个对象是否是一个类的实例
class Foo:
pass
foo_obj = Foo()
print(foo_obj)
print(foo_obj.__class__.__dict__)
print(foo_obj in Foo.__dict__) # 判断一个对象是否是类的实例
print(isinstance(foo_obj, Foo)) # 判断一个对象是否是类的实例
issubclass
python内置函数,可以传入两个参数,用于判断参数1是否是参数2的一个子类
判断一个类是否是一个类的子类
class Foo:
pass
class Goo(Foo):
pass
print(issubclass(Goo, Foo)) # True
反射
指的是通过“字符串”对 对象或类的属性进行操作
hasatter
通过字符串,判断字符串是否是对象或类的属性
class People:
country = 'China'
def __init__(self, name, age, sex):
self.name = name
self.age = age
self.sex = sex
p = People('tank', 18, 'male')
# 普通方式
print('name' in p.__dict__)
# hasatter
print(hasattr(p, 'name'))
print(hasattr(p, 'country'))
getatter
通过字符串,获取对象或类的属性4
# 普通方式
print(p.__dict__.get('name'))
# getatter
print(getattr(p, 'name', 'jason'))
setatter
通过字符串,设置对象或类的属性
setattr(p, 'level', '3.0')
print(hasattr(p, 'level'))
delatter
通过字符串,删除对象或类的属性
delattr(p, 'name')
print(hasattr(p, 'name'))
反射小练习
class Movie:
def input_cmd(self):
print('请输入命令......')
while True:
cmd = input('请输入执行的命令:').strip()
# 若输入的cmd命令是当前对象的属性
if hasattr(self, cmd):
method = getattr(self, cmd)
method()
def upload(self):
print('正在上传...')
def download(self):
print('正在下载...')
obj = Movie()
obj.input_cmd()
魔法方法
凡是类内部定义,以__开头,__结尾的方法都称之为魔法方法,又称类的内置方法
魔法方法会在某些条件成立的时候触发
__init__:在掉用类时触发
__str__:在打印对象时触发
__del__:会在程序结束时触发,销毁对象, 该方法会在最后执行
__getattr__:会在对象.属性时,属性没有的情况下才会触发
__setattr__:会在对象.属性 = 属性值的时候触发
__new__:会在__init__执行前触发
__call__:会在对象调用时触发
class Foo:
def __new__(cls, *args, **kwargs):
print(cls)
return object.__new__(cls) # 真正产生一个对象
# 若当前类的__new__没有return一个空对象,则不会触发
def __init__(self):
print('在调用类时触发...')
def __str__(self):
print('在打印对象时触发')
# 必须要有一个返回值,该返回值必须是字符串
return '我是Foo实例化出的对象'
def __del__(self):
print('对象被销毁前执行该程序')
def __getattr__(self, item):
print('会在对象.属性时,属性没有的情况下才会触发')
print(item)
# 若想打印属性的结果,必须要return一个值
# 注意:执行该方法时,外部“对象.属性=属性值”时无效
def __setattr__(self, key, value):
print('会在对象.属性 = 属性值的时候触发')
print(key, value)
print(self, 111)
self.__dict__[key] = 1234
def __call__(self, *args, **kwargs):
print(self)
print('调用对象时触发')
obj = Foo()
# print(obj)
# print(obj.x)
# obj.x = 3
# print(obj.x)
#
# obj()
魔法方法del应用:
class MyFile(object):
def __init__(self, file_name, mode='r', encoding='utf-8'):
self.file_name = file_name
self.mode = mode
self.encoding = encoding
def file_open(self):
self.f = open(self.file_name, self.mode, encoding=self.encoding)
def file_read(self):
res = self.f.read()
print(f'''
当前文件名称:{self.file_name}
当前文件内容:{res}
''')
def __del__(self):
self.f.close()
print('文件关闭成功')
f = MyFile('settings.py')
f.file_open()
f.file_read()
单例模式
什么是单例
单例模式指的是单个实例,实例指的是调用类产生的对象
为什么要使用单例
实例化多个对象会产生不同的内存地址,单例可以调用者在调用同一个对象时,都指向同一个内存地址。例如打开文件。
单例的目的:为了减少内存的占用。
class File:
def __init__(self, file_name, mode='r', encoding='utf-8'):
self.file_name = file_name
self.mode = mode
self.encoding = encoding
def open(self):
self.f = open(self.file_name, self.mode, encoding=self.encoding)
def read(self):
res = self.f.read()
return res
def close(self):
self.f.close()
obj1 = File('settings.py')
obj2 = File('settings.py')
obj3 = File('settings.py')
print(obj1)
print(obj2)
print(obj3)
'''
<__main__.File object at 0x00000143ACD7D978>
<__main__.File object at 0x00000143ACDA20B8>
<__main__.File object at 0x00000143ACDA2198>
'''
可以看出,实例化出三个对象,它们的地址都不相同
class File:
__instance = None
# 单例模式1
@classmethod
def singleton(cls, file_name):
if not cls.__instance:
obj = cls(file_name)
cls.__instance = obj
return cls.__instance
def __init__(self, file_name, mode='r', encoding='utf-8'):
self.file_name = file_name
self.mode = mode
self.encoding = encoding
def open(self):
self.f = open(self.file_name, self.mode, encoding=self.encoding)
def read(self):
res = self.f.read()
return res
def close(self):
self.f.close()
obj1 = File.singleton('settings.py')
obj2 = File.singleton('settings.py')
obj3 = File.singleton('settings.py')
print(obj1)
print(obj2)
print(obj3)
'''
<__main__.File object at 0x000001A04F472198>
<__main__.File object at 0x000001A04F472198>
<__main__.File object at 0x000001A04F472198>
'''
class File:
__instance = None
# 单例模式2
def __new__(cls, *args, **kwargs):
if not cls.__instance:
cls.__instance = object.__new__(cls)
return cls.__instance
def __init__(self, file_name, mode='r', encoding='utf-8'):
self.file_name = file_name
self.mode = mode
self.encoding = encoding
def open(self):
self.f = open(self.file_name, self.mode, encoding=self.encoding)
def read(self):
res = self.f.read()
return res
def close(self):
self.f.close()
obj1 = File('settings.py')
obj2 = File('settings.py')
obj3 = File('settings.py')
print(obj1)
print(obj2)
print(obj3)
'''
<__main__.File object at 0x00000184C9CD2198>
<__main__.File object at 0x00000184C9CD2198>
<__main__.File object at 0x00000184C9CD2198>
'''
classmethod,staticmethod,反射,魔法方法,单例模式的更多相关文章
- 面对对象高阶+反射+魔法方法+单例(day22)
目录 昨日内容 组合 封装 property装饰器 多态 鸭子类型 今日内容 classmethod staticmethod 面对对象高级 isinstance issubclass 反射(重要) ...
- python基础语法18 类的内置方法(魔法方法),单例模式
类的内置方法(魔法方法): 凡是在类内部定义,以__开头__结尾的方法,都是类的内置方法,也称之为魔法方法. 类的内置方法,会在某种条件满足下自动触发. 内置方法如下: __new__: 在__ini ...
- python之魔法方法介绍
1.1. 简介 什么是魔法方法呢?它们在面向对象的Python的处处皆是.它们是一些可以让你对类添加“魔法”的特殊方法. 它们经常是两个下划线包围来命名的(比如 __init__ , __lt__ ) ...
- python_面向对象魔法方法指南
原文: http://www.rafekettler.com/magicmethods.html 原作者: Rafe Kettler 翻译: hit9 原版(英文版) Repo: https://gi ...
- CSIC_716_20191129【面向对象高级----反射、类的内置方法(魔法方法)、单例模式】
反射 反射是通过'字符串'对 对象的属性进行操作,反射有四个内置的方法. hasattr 通过字符串 判断对象的属性或者方法是否存在 getattr 通过字符串 获取对象的属性或者方法 ...
- 面向对象相关概念与在python中的面向对象知识(魔法方法+反射+元类+鸭子类型)
面向对象知识 封装 封装的原理是,其成员变量代表对象的属性,方法代表这个对象的动作真正的封装是,经过深入的思考,做出良好的抽象(设计属性时用到),给出“完整且最小”的接口,并使得内部细节可以对外透明( ...
- 【面试必问】python实例方法、类方法@classmethod、静态方法@staticmethod和属性方法@property区别
[面试必问]python实例方法.类方法@classmethod.静态方法@staticmethod和属性方法@property区别 1.#类方法@classmethod,只能访问类变量,不能访问实例 ...
- python3 封装之property 多态 绑定方法classmethod 与 非绑定方法 staticmethod
property 特性 什么是特性property property 是一种特殊的属性,访问它时会执行一段功能(函数),然后返回值 例如 BMI指数(bmi是计算而来的,但很明显它听起来像是一个属性而 ...
- python 魔法方法
I am not a creator, I just a porter. Note: Everything is object in python. 对于Python来说一切都是对象,也就是函数的参数 ...
随机推荐
- Cesium专栏-空间分析之剖面分析(附源码下载)
Cesium Cesium 是一款面向三维地球和地图的,世界级的JavaScript开源产品.它提供了基于JavaScript语言的开发包,方便用户快速搭建一款零插件的虚拟地球Web应用,并在性能,精 ...
- ABP入门教程7 - 基础设施层更新数据库
点这里进入ABP入门教程目录 设置数据库 在基础设施层(即JD.CRS.EntityFrameworkCore)打开数据库环境设置 JD.CRS.EntityFrameworkCore/EntityF ...
- java中的IO流操作总结
概要:
- tomcat的一些优化及报错
以下为转发来,具体地址为 http://blog.csdn.net/chen3888015/article/details/7432488 环境centos5.7 tomcat6 http://apr ...
- Phoenix核心功能原理及应用场景介绍以及Calcite 查询计划生成框架介绍
Phoenix是一个开源的HBase SQL层.它不仅可以使用标准的JDBC API替代HBase Client API创建表,插入和查询HBase,也支持二级索引.事物以及多种SQL层优化. 此系列 ...
- Linux IO协议栈
图片来源自网络,保持更新:更多内容请关注 cnblogs.com/xuyaowen 参考链接: https://zhuanlan.zhihu.com/p/39721251 http://blog.yu ...
- Linux-3.14.12内存管理笔记【构建内存管理框架(2)】
前面构建内存管理框架,已经将内存管理node节点设置完毕,接下来将是管理区和页面管理的构建.此处代码实现主要在于setup_arch()下的一处钩子:x86_init.paging.pagetable ...
- 201871010126 王亚涛 《面向对象程序设计 (Java)》第十六周学习总结
内容 这个作业属于哪个课程 https://www.cnblogs.com/nwnu-daizh/ 这个作业的要求在哪里 https://www.cnblogs.com/nwnu-daizh/p/12 ...
- 201871010112-梁丽珍《面向对象程序设计(java)》第十六周学习总结
项目 内容 这个作业属于哪个课程 https://www.cnblogs.com/nwnu-daizh/ 这个作业的要求在哪里 https://www.cnblogs.com/nwnu-daizh/p ...
- FastDFS--storage文件上传和下载问题
使用FastDFS--storage文件上传出现如下bug: >>> ret = client.upload_by_filename('/home/python/Desktop/1. ...