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来说一切都是对象,也就是函数的参数 ...
随机推荐
- Microsoft Visual Studio 2017 找不到 Visual Studio Installer
Microsoft Visual Studio 2017 找不到 Visual Studio Installer ? 打开vs2017 ,选择 工具 --> 扩展和更新 --> 联机,搜索 ...
- 使用npm link 加速调试
我们在把包发布到npm上时,如果需要对本地的包进行修改,我们需要改变一个版本,重新发布.然后测试时需要更新这个包进行测试.这样的话,每一次的调试都特别麻烦.我们可以使用npm link来加速这个调试过 ...
- 安全意识第八期丨OMG!发个帖子竟然摊上大事了
互联网时代,话在网上说.钱在网上花.事在网上办,这早已成为一种习惯,越来越多的人也倾向于通过网络来获取信息. 借助现代信息技术,网络传播者通过即时通讯工具.微博.朋友圈等渠道发布信息,虽然传播起来更便 ...
- CentOS7 安装frp与开机启动
1. 下载frp程序文件 https://github.com/fatedier/frp/releases 2. 解压文件 下载后解压到自己的目录,我这里解压到/usr/local/frp: 3. 添 ...
- 11.JavaCC官方入门指南-例6
例6:计算器--添加括号.一元运算符和历史记录 1.calculator3.jj 我们只需要再添加一些特色,就可以得到一个可用的四则运算计算器.在这一版的修改中 ,我们将使得程序可以接收括号.负值 ...
- python升级带来的yum异常(解决错误File "/usr/bin/yum", line 30 except KeyboardInterrupt, e:)
解决错误File "/usr/bin/yum", line 30 except KeyboardInterrupt, e: 错误: 原因: 这是因为yum采用python作为命令解 ...
- 008.MongoDB分片群集概念及原理
一 MongoDB分片介绍 1.1 分片 Mongodb另一种集群,就是分片技术,可以满足MongoDB数据量大量增长的需求. 当MongoDB存储海量的数据时,一台机器可能不足以存储数据,也可能不足 ...
- 0day2安全——笔记4(修改临界变量)
第二章 修改临界变量 #include <stdio.h> #include <string.h> #define PASSWORD "1234567" i ...
- OMM机制(占位)
由于没有swap分区,导致系统启动omm机制,把mysql干掉
- python中copy()和deepcopy()详解
**首先直接上结论: —–我们寻常意义的复制就是深复制,即将被复制对象完全再复制一遍作为独立的新个体单独存在.所以改变原有被复制对象不会对已经复制出来的新对象产生影响.—–而浅复制并不会产生一个独立的 ...