加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

常用魔术方法总结

发布时间:2020-12-20 11:00:06 所属栏目:Python 来源:网络整理
导读:python 中常见的魔术方法: 1、__getattr__(self,item): 方法 在访问对象的item属性的时候,如果对象和他的父类并没有这个相应的属性,方法,那么将会调用这个方法来处理。有相应的属性或方法时调用对象实例的相应属性或方法。 参数 item 代表 调用的属性或

python 中常见的魔术方法:
1、__getattr__(self,item): 方法
在访问对象的item属性的时候,如果对象和他的父类并没有这个相应的属性,方法,那么将会调用这个方法来处理。有相应的属性或方法时调用对象实例的相应属性或方法。
参数 item 代表 调用的属性或方法。

class Foo:
def __init__(self,x):
self.x = x

@property
def get_01(self):
print(111)
return self.x

def __getattr__(self,item):
# 当实例对象的的 f.a属性不存再时执行的操作
print(‘执行的是我‘)
print(item)
return self.x
f1 = Foo(10)
print(f1.get_01) # 111,10
print(f1.a) # 执行的是我,a,10
print(f1.get_02) # 执行的是我,get_02,10

2.__setattr__(self,item,value): 方法
会拦截所有属性的的赋值语句。如果定义了这个方法,self.arrt = value 就会变成self,__setattr__("attr",value).这个需要注意。
当在__setattr__方法内对属性进行赋值是,不可使用self.attr = value,因为他会再次调用self,value),则会形成无穷递归循环,
最后导致堆栈溢出异常。应该通过对属性字典做索引运算来赋值任何实例属性,也就是使用self.__dict__[‘name‘] = value.

class Student:
def __init__(self,item):
self.x=item
def __getattr__(self,item):
return item + ‘ is not exits‘

def __setattr__(self,key,value):
print("执行我")
self.__dict__[key] = value+2


s = Student(10) # # 调用__setattr__ 方法 执行我
print(s.x) # 12
print(s.name) # 调用__getattr__方法 输出‘name is not exits‘
s.age = 1 # 调用__setattr__ 方法
print(s.age) # 输出 3

3、__str__(self): 方法 打印实例对象时 自动被调用
class Student:
def __init__(self,item):
self.x=item
def __str__(self):
print("打印对象时调用")
return "111"

s=Student(10) print(s) # 打印对象时调用 111

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读