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来说一切都是对象,也就是函数的参数 ...
随机推荐
- PHP对URL进行字符串编码
urlencode($url1) urldecode($url) //对URL进行字符串编码和解码 $url1 = 'https://www.baidu.com/uploade/img/123.png ...
- s3c2440裸机-时钟编程(二、配置时钟寄存器)
s3c2440裸机编程-时钟编程(二.配置时钟寄存器) 1.2440时钟时序 下图是2440时钟配置时序: 1.上电后,nRESET复位信号拉低,此时cpu还无法取指令工作. 2.nRESET复位信号 ...
- Python爬虫(学习准备)
编码格式的认识: 字符:各种文字和符号的统称 字符集:多个字符的集合 字符集包括:ASCII字符集,GB2312字符集,GB18030,Unicode字符集等 1个字符ASCII编码占1个字节,用Un ...
- Codeforces Round #588 (Div. 2)
传送门 A. Dawid and Bags of Candies 乱搞. Code #include <bits/stdc++.h> #define MP make_pair #defin ...
- Collection接口综述
Collection接口 Collection是集合类基本的接口,它不提供具体的实现,集合类都继承自Collection接口,Collection代表的是一种规则,它包含的元素必须符合某种规则,比如有 ...
- 【python爬虫】cookie & session
一.什么是cookie? cookie是指网站为了鉴别用户身份,进行会话跟踪而存储在客户端本地的数据. 二.什么是session? 本来的含义是指有始有终的一些列动作,而在web中,session对象 ...
- 一文学会 TypeScript 的 82% 常用知识点(上)
前端专栏 2019-11-22 19:17:55 对于前端从业者来说,TypeScript(以下简称 TS)已经不算是新技术. Vue3 的源码基于 TS 编写, Angular 项目默认支持 TS ...
- kindEditor 修改上传图片的路径
压缩过的js类似
- 【swoole】结合swoole 和 nsq 的实际应用
集合 swoole 的框架设计 为了减少理解度,我尽量的从源头开始引入 1. nsq 案例中是使用 swoole 结合一个php 框架实现的是 NSQ 订阅功能. 启动命令: sudo bash /w ...
- spring-framework-core-ioc Container
阅读须知 实例化bean xml方式实例化bean 注解方式实例化bean java方式实例化bean ClassPathXmlApplication和AnnotationConfigApplicat ...