python3 常见的魔法属性
1.
__setitem__,__getitem,__delitem__
用于索引操作,如字典。以上分别表示设置、获取、删除数据
有点类似于之前的__getattr__,__setattr__,__delattr__
只不过是前者是对对象使用.(点)的方式进行操作
后者则是使用[" "](中括号)形式操作。
举例:
1 class Person():
2 def __init__(self,name,addr):
3 self.name=name
4 self.adr=addr
5 def __getitem__(self, item):
6 print(self.__dict__[item])
7
8 def __setitem__(self, key, value):
9 self.__dict__[key]=value
10
11 def __delitem__(self, key):
12 self.__dict__[key].pop()
13
14 p=Person("pig","beijing")
15 print(p["name"])
16 p["age"]=19
17 print(p.__dict__)
18 class Person():
19 def __init__(self,name,addr):
20 self.name=name
21 self.adr=addr
22 def __getitem__(self, item):
23 print(self.__dict__[item])
24
25 def __setitem__(self, key, value):
26 self.__dict__[key]=value
27
28 def __delitem__(self, key):
29 self.__dict__.pop(key)
30
31 p=Person("pig","beijing")
32 print(p["name"])
33 p["age"]=19
34 print(p.__dict__)
35 del p["name"]
36 print(p.__dict__)
37
38
39 ##############
40 pig
41 None
42 {'adr': 'beijing', 'age': 19, 'name': 'pig'}
43 pig
44 None
45 {'adr': 'beijing', 'age': 19, 'name': 'pig'}
46 {'adr': 'beijing', 'age': 19}
2.
__getatrribute__和__getattr__的区别: __getattr__只有在使用点调用属性且属性不存在的时候才会触发
1 class Person():
2 def __init__(self,name,addr):
3 self.name=name
4 self.adr=addr
5 def __getattr__(self, item):
6 print("__getattr__只有在使用点调用属性且属性不存在的时候才会触发")
7
8 p=Person("小周周","成都市")
9 print(p.name)
10 p.age####不存在的属性
11 print(p.__dict__)
12
13
14 ###########
15 小周周
16 __getattr__只有在使用点调用属性且属性不存在的时候才会触发
17 {'adr': '成都市', 'name': '小周周'}
__getatrribute__不管属性存在不存在,始终都会被触发
1 class Person():
2 def __init__(self,name,addr):
3 self.name=name
4 self.adr=addr
5
6 def __getattribute__(self, item):
7 print("不管你是否存在,我都会执行。啦啦啦,被我打败了")
8 p=Person("小周周","成都市")
9 print(p.name)
10 p.age####不存在的属性
11 print(p.__dict__)
12
13 #################
14 不管你是否存在,我都会执行。啦啦啦,被我打败了
15 None
16 不管你是否存在,我都会执行。啦啦啦,被我打败了
17 不管你是否存在,我都会执行。啦啦啦,被我打败了
18 None
但是:当__getattribute__与__getattr__同时存在,只会执行__getattrbute__,除非__getattribute__在执行过程中抛出异常AttributeError,后面才会去执行__getattr__
1 class Person():
2 def __init__(self,name,addr):
3 self.name=name
4 self.adr=addr
5 def __getattr__(self, item):
6 print("__getattr__只有在使用点调用属性且属性不存在的时候才会触发")
7
8 def __getattribute__(self, item):
9 print("不管你是否存在,我都会执行。啦啦啦,被我打败了")
10 p=Person("小周周","成都市")
11 print(p.name)
12 p.age####不存在的属性
13 print(p.__dict__)
14
15
16 ###########
17 不管你是否存在,我都会执行。啦啦啦,被我打败了
18 None
19 不管你是否存在,我都会执行。啦啦啦,被我打败了
20 不管你是否存在,我都会执行。啦啦啦,被我打败了
21 None
1 class Person():
2 def __init__(self,name,addr):
3 self.name=name
4 self.adr=addr
5 def __getattr__(self, item):
6 print("__getattr__只有在使用点调用属性且属性不存在的时候才会触发")
7
8 def __getattribute__(self, item):
9 print("不管你是否存在,我都会执行。啦啦啦,被我打败了")
10 raise AttributeError("小弟,大哥我报错了,接下来你自己看着办")
11 p=Person("小周周","成都市")
12 print(p.name)
13 p.age####不存在的属性
14 print(p.__dict__)
15
16
17 #####################
18 不管你是否存在,我都会执行。啦啦啦,被我打败了
19 __getattr__只有在使用点调用属性且属性不存在的时候才会触发
20 None
21 不管你是否存在,我都会执行。啦啦啦,被我打败了
22 __getattr__只有在使用点调用属性且属性不存在的时候才会触发
23 不管你是否存在,我都会执行。啦啦啦,被我打败了
24 __getattr__只有在使用点调用属性且属性不存在的时候才会触发
25 None
__getattr__只有在使用点调用属性且属性不存在的时候才会触发
3.
__doc__
表示描述类的描述信息
class TV():
"""这个是关于电视的相关操作"""
def func(self):
pass
####################
这个是关于电视的相关操作
4.
__module__ 和 __class__
__module__ 表示当前操作的对象在那个模块;
__class__ 表示当前操作的对象的类是什么。
class TV():
"""这个是关于电视的相关操作"""
def __init__(self,name,age):
self.name=name;
self.age=age
main.py
__author__ = 'Administrator'
from _demo1 import TV
obj=TV("小猪猪",18)
print(obj.__module__)
print(obj.__class__)
###################
_demo1
<class '_demo1.TV'>
5.
__init__
初始化方法,通过类创建对象时,自动触发执行
__author__ = 'Administrator'
class Demo():
def __init__(self):
print("我自动执行咯======")
def list_add(self):
for i in range(2):
print(i)
demo=Demo()
demo.list_add()
###############
我自动执行咯======
0
1
6.
__del__
当对象在内存中被释放时,自动触发执行
注:此方法一般无须定义,因为Python是一门高级语言,程序员在使用时无需关心内存的分配和释放,因为此工作都是交给Python解释器来执行,
所以,__del__的调用是由解释器在进行垃圾回收时自动触发执行的。
__author__ = 'Administrator'
class Demo():
def __init__(self):
print("我自动执行咯======")
def __del__(self):
print("我执行咯++++++++++++++++++++")
demo=Demo()
###########################
我自动执行咯======
我执行咯++++++++++++++++++++
7.
__call__
对象后面加括号,触发执行。
注:__init__方法的执行是由创建对象触发的,即:对象 = 类名() ;而对于 __call__ 方法的执行是由对象后加括号触发的,即:对象() 或者 类()
__author__ = 'Administrator'
class Demo():
def __init__(self):
print("我自动执行咯======")
def __call__(self, *args, **kwargs):
print("我执行咯********************")
demo=Demo()
demo()
###########################
我自动执行咯======
我执行咯********************
8.
__dict__
类或对象中的所有属性
类的实例属性属于对象;类中的类属性和方法等属于类.
__author__ = 'Administrator'
class Demo():
county="中国"
def __init__(self,name,age):
self.name=name
self.age=age
def show_info(self):
print("我的名字是: %s" %self.name)
print("我的年龄是: %d" %self.age)
demo=Demo("彭伊伊",100)
# 获取类的属性和方法
print(Demo.__dict__)
demo.show_info()
# 获取对象的属性
print(demo.__dict__)
####################
{'__doc__': None, 'show_info': <function Demo.show_info at 0x0000000002B5CA60>, 'county': '中国', '__module__': '__main__', '__init__': <function Demo.__init__ at 0x0000000002B5C8C8>, '__weakref__': <attribute '__weakref__' of 'Demo' objects>, '__dict__': <attribute '__dict__' of 'Demo' objects>}
我的名字是: 彭伊伊
我的年龄是: 100
{'name': '彭伊伊', 'age': 100}
9.
__str__
如果一个类中定义了__str__方法,那么在打印 对象 时,默认输出该方法的返回值。
__author__ = 'Administrator'
class Demo():
def __init__(self):
print("我自动执行咯======")
def __call__(self, *args, **kwargs):
print("我执行咯********************")
def __str__(self):
return "青春荒唐愿花开如常"
demo=Demo()
print(demo)
demo()
######################
我自动执行咯======
青春荒唐愿花开如常
我执行咯********************


浙公网安备 33010602011771号