#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
class People():
"""A simple attempt to model a people."""
def __init__(self, name, age):
"""Initialize name and age attributes."""
self.name = name
self.age = age
def __setattr__(self, key, value):
print("=--setattr-->")
print("%s:%s" % (key, value))
self.__dict__[key] = value
def __delattr__(self, item):
print("=--delattr-->")
print("delattr: %s" % (item))
self.__dict__.pop(item)
def __getattr__(self, item):
print("=--getattr-->")
print("getattr: %s" % (item))
print(item, type(item))
print()
qiang = People('qiang', 16)
print(qiang.__dict__)
print()
yong = People('yong', 19)
print(yong.__dict__)
print()
del qiang.name
print(qiang.__dict__)
print()
del yong.age
print(yong.__dict__)
print()
print(yong.beauty)
print()
yong.__delattr__("name")
print(yong.__dict__)
print()
qiang.__setattr__("age", 99)
print(qiang.__dict__)
/usr/bin/python2.7 /home/strong/git_workspace/MonoGRNet/test.py --train_batch_size 64 --is_train False --gpus 0
=--setattr-->
name:qiang
=--setattr-->
age:16
{'age': 16, 'name': 'qiang'}
=--setattr-->
name:yong
=--setattr-->
age:19
{'age': 19, 'name': 'yong'}
=--delattr-->
delattr: name
{'age': 16}
=--delattr-->
delattr: age
{'name': 'yong'}
=--getattr-->
getattr: beauty
beauty
None
=--delattr-->
delattr: name
{}
=--setattr-->
age:99
{'age': 99}
Process finished with exit code 0
__serattr__
:
当设置对象的属性时会触发,例如 self.name = name
,有几次赋值会触发几次运行。
__delattr__
:
当删除对象属性时会触发,例如 del qiang.name
。
__getattr__
:
此内置方法比较特殊,当对象的属性不存在时会触发执行 __getattr__
。