当前位置:网站首页>Custom attribute access__ getattribute__/ Settings__ setattr__/ Delete__ delattr__ method
Custom attribute access__ getattribute__/ Settings__ setattr__/ Delete__ delattr__ method
2022-07-06 02:51:00 【chuntian_ tester】
Catalog
When the attribute search is not found ( Report errors AttriErro) when , This method is triggered
When looking for attributes , This method will be called at the first time
When setting properties , This method will be triggered to set properties
stay del Object properties , This method is triggered
Define magic methods to define attribute access of class instances .
summary : When the method of the parent class cannot meet its functional requirements , You can override the parent method , When rewriting, add the functions you want to add , adopt super(). Parent class method () To extend the function of the parent method , such , Rewrite your own method , It has the function of parent method , It also has its own added functions .
1.object.__getattr__
When the attribute search is not found ( Report errors AttriErro) when , This method is triggered
class Attr:
def __getattr__(self, item):
# When accessing object properties , If the attribute does not exist , And an error AttrError when , This method is triggered .
print('---getattr--- Method triggered ')
return 666
if __name__ == '__main__':
a = Attr()
print(a.name)
# Output :
# ---getattr - -- Method triggered
# 6662.object.__getattribute__
When looking for attributes , This method will be called at the first time
class Attr:
def __getattr__(self, item):
# When accessing object properties , If the attribute does not exist , And an error AttrError when , This method is triggered .
print('---getattr--- Method triggered ')
# Call the parent class when triggered getattribute Method , Find properties , If not , Throw out AttributeError: 'Attr' object has no attribute 'name'
object.__getattribute__(self, item)
def __getattribute__(self, item):
# When accessing properties , This method will be triggered for the first time to find properties
print('---getattribute--- Method triggered ')
# Add custom function
print(' Custom function is added here ')
# After adding the customization function , Calling the getattribute Method to find properties
return super().__getattribute__(item)
if __name__ == '__main__':
a = Attr()
a.name = ' Springfield '
print(a.name)
# Output :
---getattribute - -- Method triggered
Custom function is added here
Springfield
3.object.__setattr__
When setting properties , This method will be triggered to set properties
class Attr:
def __setattr__(self, key, value):
# When setting properties for objects , This method is triggered
print('---setattr--- Method triggered ')
print(key)
print(value)
if __name__ == '__main__':
a = Attr()
a.name = ' Springfield '
# Output :
---setattr - -- Method triggered
name
Springfield class Attr:
def __setattr__(self, key, value):
# When setting properties for objects , This method is triggered
print('---setattr--- Method triggered ')
if key == 'name':
# Locked object name attribute , Cannot be modified outside the object , Regardless of the outside a.name Set to how much ,name Properties are never modified
super().__setattr__(key, " Sheep Baa Baa ")
else:
# The object property set is not name, It can be modified normally
super().__setattr__(key, value)
if __name__ == '__main__':
a = Attr()
a.name = ' Springfield '
print(a.name)
a.age = 130
print(a.age)
# Output :
---setattr - -- Method triggered
Sheep Baa Baa
---setattr - -- Method triggered
1304.object.__delattr__
stay del Object properties , This method is triggered
class Attr:
def __delattr__(self, item):
# This method will be triggered when deleting attributes
print('---delattr--- Method triggered ')
if __name__ == '__main__':
a = Attr()
a.name = ' Springfield '
del a.name
# Output :
---delattr - -- Method triggered class Attr:
def __delattr__(self, item):
# This method will be triggered when deleting attributes
print('---delattr--- Method triggered ')
# Extend the functionality
print(' Here are the extended functions ')
# Calling the delattr Method to delete a property
super().__delattr__(item)
print(f' attribute {item} It has been deleted ')
if __name__ == '__main__':
a = Attr()
a.name = ' Springfield '
del a.name
print(a.name)
# Output :
---delattr - -- Method triggered
Here are the extended functions
attribute name It has been deleted
AttributeError: 'Attr' object has no attribute 'name'class Attr:
def __delattr__(self, item):
# This method will be triggered when deleting attributes
print('---delattr--- Method triggered ')
# Extend the functionality , If the attribute you want to delete is name, Just refuse , Can't delete
if item == 'name':
print(f'{item} Attribute cannot be deleted ') # Protect name Properties are not deleted
else:
# Calling the delattr Method to delete a property
super().__delattr__(item)
print(f' attribute {item} It has been deleted ')
if __name__ == '__main__':
a = Attr()
a.name = ' Springfield '
del a.name
print(a.name)
# Output :
---delattr - -- Method triggered
name Attribute cannot be deleted
Springfield
边栏推荐
- 解决:AttributeError: ‘str‘ object has no attribute ‘decode‘
- Deeply analyze the chain 2+1 mode, and subvert the traditional thinking of selling goods?
- What should we pay attention to when using the built-in tool to check the health status in gbase 8C database?
- 深度解析链动2+1模式,颠覆传统卖货思维?
- Large scale DDoS attacks take Myanmar offline
- [unity3d] GUI control
- MySQL advanced notes
- [ruoyi] set theme style
- 不赚钱的科大讯飞,投资价值该怎么看?
- Pat 1046 shortest distance (20 points) simulation
猜你喜欢
![[Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 12](/img/b1/926d9b3d7ce9c5104f3e81974eef07.jpg)
[Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 12

Codeworks 5 questions per day (1700 average) - day 6

【Kubernetes 系列】一文学会Kubernetes Service安全的暴露应用

淘宝焦点图布局实战

MySQL advanced notes

Referenceerror: primordials is not defined error resolution

RobotFramework入门(一)简要介绍及使用

米家、涂鸦、Hilink、智汀等生态哪家强?5大主流智能品牌分析

Li Kou today's question -729 My schedule I

Httprunnermanager installation (III) - configuring myql Database & initialization data under Linux
随机推荐
原型图设计
tcpdump: no suitable device found
[Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 10
力扣今日題-729. 我的日程安排錶 I
CobaltStrike-4.4-K8修改版安装使用教程
DDoS "fire drill" service urges companies to be prepared
【若依(ruoyi)】ztree 自定义图标(iconSkin 属性)
2345文件粉碎,文件强力删除工具无捆绑纯净提取版
RobotFramework入门(二)appUI自动化之app启动
Patch NTP server at the beginning of DDoS counterattack
Looking at the trend of sequence modeling of recommended systems in 2022 from the top paper
建模规范:命名规范
Zhang Lijun: penetrating uncertainty depends on four "invariants"
Bigder: I felt good about the 34/100 interview, but I didn't receive the admission
ERA5再分析资料下载攻略
【Kubernetes 系列】一文学会Kubernetes Service安全的暴露应用
A copy can also produce flowers
Apt installation ZABBIX
解决:AttributeError: ‘str‘ object has no attribute ‘decode‘
MySQL winter vacation self-study 2022 11 (8)