Python入门-面向对象-特殊方法



调用拦截功能
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入门-面向对象-特殊方法的更多相关文章
- Python入门 - 面向对象
python很好的支持面向对象编程,本节主讲类的定义,类的构造方法,类的继承与方法重写,类的多继承. 一.类的定义 class Myclass() : def prt(self, str) : pri ...
- Python之面向对象:方法
一.类的三种方法 1.实例方法 def func(self): 由对象调用:至少一个self参数:执行普通方法时,自动将调用该方法的对象赋值给self: 只能通过实例调用 2.静态方法 @stat ...
- Python入门之format()方法
在此列出format()方法的一些基本使用: >>> '{}{}{}'.format('圆周率是',3.1415926,'...') '圆周率是3.1415926...' >& ...
- Python入门-面向对象-装饰器
1.变量作用域 全局变量和局部变量 #变量是有作用域的,分为全局变量和局部变量 num = 100 #这是全局变量 def change(): """ 查看变量作用域 & ...
- Python入门-面向对象三大特性-封装
一.封装 封装,顾名思义就是将内容封装到某个地方,以后再去调用被封装在某处的内容. 所以,在使用面向对象的封装特性时,需要: 将内容封装到某处 从某处调用被封装的内容 第一步:将内容封装到某处 sel ...
- Python入门-面向对象三大特性-多态
Pyhon不支持多态并且也用不到多态,多态的概念是应用于Java和C#这一类强类型语言中,而Python崇尚"鸭子类型".
- Python入门-面向对象三大特性-继承
面向对象中的继承和现实生活中的继承相同,即:子可以继承父的内容. 例如: 猫可以:喵喵叫.吃.喝.拉.撒 狗可以:汪汪叫.吃.喝.拉.撒 如果我们要分别为猫和狗创建一个类,那么就需要为 猫 和 狗 实 ...
- Python入门之面向对象的__init__和__new__方法
Python入门之面向对象的__init__和__new__方法
- Python入门篇-面向对象概述
Python入门篇-面向对象概述 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.语言的分类 面向机器 抽象成机器指令,机器容易理解 代表:汇编语言 面向过程 做一件事情,排出个 ...
随机推荐
- LGP4609题解
题意简单明确( 很容易知道最高的位置一定是左边能看到最高的和右边能看到最高的.于是我们考虑一个 dp: 设 \(dp[n][A][B]\) 表示长度为 \(n\) 的排列,左边有 \(A\) 个 ba ...
- 网易互娱23届实习笔试_3x3锯齿数独
一.输入: 输入一个3x3数独,字符'.'代表空输入三个宫的域,每个宫包括三个位置,[0,0]表示0行0列 二.输出要求: 1.每个宫里最终123各出现一次, 2.数独中的行列里不出现重复字符: 输出 ...
- python-用代码实现队列,处理斐波那契数列
队列在进行数据操作时必须遵循"先进先出(Firstin Firstout,FIFO)"的原则,这一特点决定了队列的基本操作需要在其两端进行 队列(Queue)的基本操作通常在队列的 ...
- Mysql数据库索引的使用
1.索引的使用 查询 表的锁show index from qk_auth_employee 2.走索引 EXPLAIN SELECT * from qk_auth_employee where Da ...
- Python之GUI用户界面Tkinter(一)
Label Label(标签)组件用于在屏幕上显示文本或图像,仅能显示单一字体的文本 •参数 Label(master=None, **options) (class)**options 组件选项,下 ...
- Spring Data Jpa 更新操作
第一步,通过Repository对象把实体根据ID查询出来 第二部,往查出来的实体对象进行set各个字段 第三步,通过Repository接口的save方法进行保存 保存和更新方式(已知两种) 第一种 ...
- Dubbo 支持分布式事务吗?
目前暂时不支持,可与通过 tcc-transaction 框架实现 介绍:tcc-transaction 是开源的 TCC 补偿性分布式事务框架 Git 地址:https://github.com/c ...
- Spring配置文件?
Spring配置文件是个XML 文件,这个文件包含了类信息,描述了如何配置它们,以及如何相互调用.
- CopyOnWriteArrayList 可以用于什么应用场景?
CopyOnWriteArrayList(免锁容器)的好处之一是当多个迭代器同时遍历和修改这 个列表时,不会抛出 ConcurrentModificationException.在 CopyOnWri ...
- spring 自动装配 bean 有哪些方式?
Spring容器负责创建应用程序中的bean同时通过ID来协调这些对象之间的关系.作为开发人员,我们需要告诉Spring要创建哪些bean并且如何将其装配到一起. spring中bean装配有两种方式 ...