调用拦截功能

class Message:
def send(self,info):
print("消息发送:",info)
class Me:
def __getattribute__(self, item):
print("attribute:", item) #执行拦截的操作
return object.__getattribute__(self, item) # 放开拦截的操作
def send(self,info):
print("消息发送:",info) class Lanjie:
def __getattribute__(self, item):
if item == "content":
return "这是拦截信息"
elif item == "send":
return self.other # 返回其他方法的引用
else:
return object.__getattribute__(self, item) # 放开拦截
def send(self,info):
print("消息发送:",info)
def other(self, note):
print("【替换方法】other:", note) if __name__ == '__main__':
m = Message()
print("=============不拦截代码演示:=============")
m.info="百度一下"
print(m.info)
m.send("www.baidu.com")
print("============拦截代码演示:=============")
me = Me()
me.info = "www.google.com"
print(me.info) #调用拦截
me.send("www.google.com")#调用拦截 #所有的拦截,都是自动完成的
print("============拦截后替换方法演示:=============")
lj = Lanjie()
lj.content = "lanjie的content"
print(lj.send("www.com"))

获取属性字典

class Message(object):
def __init__(self, note):
self.__note = note
class Me:
def __init__(self, note):
self.__note = note # 定义私有属性
def remove_note(self): #note为属性封装,通过类的内部才可以进行访问
del self.__note
def get_note(self):
return self.__note def __setattr__(self, key, value):
print("【setattr】key={},value={}".format(key, value))
def __getattr__(self, item):
print("【getattr】item=", item)
def __delattr__(self, item):
print("【del attr】item =", item) class M:
def __init__(self, note):
self.__note = note # 定义私有属性
def remove_note(self): #note为属性封装,通过类的内部才可以进行访问
del self.__note
def get_note(self):
return self.__note def __setattr__(self, key, value):
print("【setattr】key={},value={}".format(key, value))
self.__dict__[key] = value
def __getattr__(self, item):
print("【getattr】item=", item)
return "{}属性不存在,没有返回值".format(item)
def __delattr__(self, item):
print("【del attr】item =", item)
self.__dict__.pop(item) # 从字典里面删除属性
if __name__ == '__main__':
m = Message("note属性")
m.content = "www.baidu.com"
print(m.__dict__)
# 程序中msg实例化对象的两个属性,都保存在dict字典中
# 设置属性拦截:必须手工设置dict参数数据
# 获取属性拦截:当属性不存在的时候才会拦截
# 删除属性拦截:
# "setattr, getattr, delattr")
print("========开始属性监听=========")
me = Me("www.google.com")
print("获取存在的属性:", me.get_note())
print("获取不存在的属性:", me.content)
me.remove_note()
print("========属性监听放开=========")
m = M("www.google.com")
print("获取存在的属性:", m.get_note())
print("获取不存在的属性:", m.content)
m.remove_note()

获取子类实例化的信息

# 子类获取父类的实例化,可以定义父类的元数据

class Parent:
def __init__(self):
print("parent的初始化init")
def __init_subclass__(cls, **kwargs):
print("父类parent_subclass:", cls)
print("父类parent_subclass:", kwargs) class Sub(Parent, url="www.baidu.com", title="百度"):
def __init__(self):
print("子类sub的init") if __name__ == '__main__':
sub = Sub() """
父类parent_subclass: <class '__main__.Sub'>
父类parent_subclass: {'url': 'www.baidu.com', 'title': '百度'}
子类sub的init
"""

自定义迭代

class Message:
def __init__(self, max):
self.__max = max
self.__foot = 0
def __iter__(self):
return self
def __next__(self):
if self.__foot >= self.__max:
raise StopIteration() #如果死循环,停止迭代
else:
val = self.__max - self.__foot
self.__foot += 1
return val
if __name__ == '__main__':
m = Message(10)
for i in m:
if i ==1:
break # 不用break结束,就会死循环
print(i, end=",")
#执行结果:10,9,8,7,6,5,4,3,2,

对象反转

class Message:
def __init__(self):
self.__mlist = ["百度", "阿里", "腾讯"]
def get_list(self):
return self.__mlist
def __reversed__(self):
self.__mlist = reversed(self.__mlist) if __name__ == '__main__':
m = Message()
print("下面是自定义的反转操作:")
reversed(m) for i in m.get_list():
print(i, end=",")
"""
下面是自定义的反转操作:
腾讯,阿里,百度,
"""

字典操作支持

#字典获取为key,value,以及字典【】
# 与字典的操作一致 class Message:
def __init__(self):
self.__map = {}
def __setitem__(self, key, value):
print("【set item】设置数据:key={}, value={}".format(key, value))
self.__map[key] = value
def __getitem__(self, item):
print("【get item】获取数据:item=", item)
return self.__map[item]
def __len__(self):
return len(self.__map)
def __delitem__(self, key):
print("【del item】马上删除数据:item=", key)
self.__map.pop(key)
if __name__ == '__main__':
m = Message()
print("=====设置数据======")
m["百度"] = "www.baidu.com"
print("=====查询获取======")
print(m["百度"])
print("=====获取个数======")
print("获取元素个数:", len(m))
print("=====删除======")
del m["百度"]
"""
=====设置数据======
【set item】设置数据:key=百度, value=www.baidu.com
=====查询获取======
【get item】获取数据:item= 百度
www.baidu.com
=====获取个数======
获取元素个数: 1
=====删除======
【del item】马上删除数据:item= 百度
"""

Python入门-面向对象-特殊方法的更多相关文章

  1. Python入门 - 面向对象

    python很好的支持面向对象编程,本节主讲类的定义,类的构造方法,类的继承与方法重写,类的多继承. 一.类的定义 class Myclass() : def prt(self, str) : pri ...

  2. Python之面向对象:方法

    一.类的三种方法 1.实例方法 def func(self): 由对象调用:至少一个self参数:执行普通方法时,自动将调用该方法的对象赋值给self: 只能通过实例调用   2.静态方法 @stat ...

  3. Python入门之format()方法

    在此列出format()方法的一些基本使用: >>> '{}{}{}'.format('圆周率是',3.1415926,'...') '圆周率是3.1415926...' >& ...

  4. Python入门-面向对象-装饰器

    1.变量作用域 全局变量和局部变量 #变量是有作用域的,分为全局变量和局部变量 num = 100 #这是全局变量 def change(): """ 查看变量作用域 & ...

  5. Python入门-面向对象三大特性-封装

    一.封装 封装,顾名思义就是将内容封装到某个地方,以后再去调用被封装在某处的内容. 所以,在使用面向对象的封装特性时,需要: 将内容封装到某处 从某处调用被封装的内容 第一步:将内容封装到某处 sel ...

  6. Python入门-面向对象三大特性-多态

    Pyhon不支持多态并且也用不到多态,多态的概念是应用于Java和C#这一类强类型语言中,而Python崇尚"鸭子类型".

  7. Python入门-面向对象三大特性-继承

    面向对象中的继承和现实生活中的继承相同,即:子可以继承父的内容. 例如: 猫可以:喵喵叫.吃.喝.拉.撒 狗可以:汪汪叫.吃.喝.拉.撒 如果我们要分别为猫和狗创建一个类,那么就需要为 猫 和 狗 实 ...

  8. Python入门之面向对象的__init__和__new__方法

    Python入门之面向对象的__init__和__new__方法

  9. Python入门篇-面向对象概述

    Python入门篇-面向对象概述 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.语言的分类 面向机器 抽象成机器指令,机器容易理解 代表:汇编语言 面向过程 做一件事情,排出个 ...

随机推荐

  1. svn服务支持网页显示并增加在线预览功能,支持视频在线播放

    1.svn服务器支持网页显示 VisualSVN Server是一个非常不错的SVN Server程序,方便,直观,用户管理也异常方便.不过,它本身并没有提供在线修改密码的功能.由于在实际使用过程中, ...

  2. VS Code配置Python环境

    Visual Studio Code配置Python环境 目录 Visual Studio Code配置Python环境 1.安装Python环境 2.安装VS Code 2.1 下载 2.2 配置中 ...

  3. LGP6694题解

    第一眼似乎很困难,实际上非常简单( 好吧这题我做了一个小时( 首先期望具有线性性,我们转化为计算点对对答案的贡献. 发现相对位置一样的点对对答案的贡献是一样的.我们把相对位置一样的点对铃出来,乘了之后 ...

  4. 今天我自己第一次写了一个Windows批处理bat脚本,一起学习一下吧。

    今天我自己第一次写了一个Windows批处理bat脚本,备注一下 事情原由:自己使用Java开发了一个加解密的工具.但是当把工具给别人使用的时候,别人还需要把代码编译打包, 然后还需要看一下代码里面的 ...

  5. 使用数据库、Redis、ZK分别实现分布式锁!

    分布式锁三种实现方式: 基于数据库实现分布式锁: 基于缓存(Redis等)实现分布式锁: 基于Zookeeper实现分布式锁: 基于数据库实现分布式锁 悲观锁 利用select - where - f ...

  6. Python之VSCode

    在学习Python的过程中,一直没有找到比较趁手的第三方编辑器,用的最多的还是Python自带的编辑器.由于本人用惯了宇宙第一IDE(Visual Studio),所以当Visual Studio C ...

  7. DDOS防御实验----反射器的安全配置

    0x01 环境 共包含三台主机 一台centos7.3 为attact主机,装有python +Scapy 一台centos7.3,server,装有bind9 ntp memcached,作为DDO ...

  8. Cobalt Strike之网站克隆

    点击 attack --> Web-dirve-by --> clone file 填写你要克隆的网站.带有端口 Clone URL:克隆目标网站的URL 注意问题:URL需要添加http ...

  9. S7-1200学习记录

    型号:CPU 1212C DC/DC/DC 硬件包括CPU模块.信号模块(输入输出).通信模块.屏幕面板 1.通信模块 S7-1200最多可以添加3块通信模块,可以使用点对点通信模块.PROFIBUS ...

  10. 浅谈systemd原理和应用

    多不说,直接上代码(可谓配置): [Unit] Description=demo app After=network-is-online.target [Service] Type=Simple Ex ...