day7-类的特殊成员方法

 1 #coding:utf-8
 2 
 3 from cc13 import Dog 
 4 
 5 print('-'*30)
 6 d = Dog('lulu')
 7 # 打印当前操作的对象在哪个模块
 8 print(d.__module__)
 9 # 打印当前操作的对象在哪个类
10 print(d.__class__)
11 
12 class Dog(object):
13     # 类的描述信息
14     """此类是形容Dog这个类"""
15 
16     food = 'baozi'
17  
18     # 构造方法,通过类创建对象时自动触发执行
19     def __init__(self,name):
20         self.name = name
21 
22     def eat(self):
23         print("{0} is eating".format(self.name))
24 
25     # 析构方法,当兑现在内存中释放时自动触发执行,一般无需定义
26     def __del__(self):
27         print("del...run")
28 
29     # 若想实例化后按obj()调用,则需定义call方法
30     def __call__(self, *args, **kwargs):  
31         print("running call",args,kwargs)
32 
33     # 定义对象返回值
34     def __str__(self):
35         return "<obj:{0}>".format(self.name)        
36 
37     # 定义索引操作(没有定义只能用obj.属性获取),获取数据
38     def __getitem__(self, key):
39         print('__getitem__:',key)
40 
41     # 设置数据
42     def __setitem__(self, key, value):
43         print('__setitem__:',key,value)
44  
45     # 删除数据
46     def __delitem__(self, key):
47         print('__delitem__',key)
48         
49 
50 print('-'*30)
51 # 打印类的描述信息 
52 print(Dog.__doc__)   
53 
54 print('-'*30)
55 d2 = Dog('lulu')
56 d2(1,2,3,{'name':'lulu'})
57 
58 print('-'*30)
59 # 打印类中的所有成员,不包括实例属性
60 print(Dog.__dict__)
61 # 打印实例中所有属性,不包括类属性
62 print(d2.__dict__)
63 
64 print('-'*30)
65 # 没有定义str方法前输出:<__main__.Dog object at 0x029B0F50>
66 print(d2)
67 
68 print('-'*30)
69 # 自动触发__setitem__
70 d2['age'] = 3
71 # 自动触发__getitem__
72 print(d2['age'])
73 # 自动触发__delitem__
74 del d2['age']
75 
76 
77 >>> 
78 ------------------------------
79 cc13
80 <class 'cc13.Dog'>
81 ------------------------------
82 此类是形容Dog这个类
83 ------------------------------
84 ('running call', (1, 2, 3, {'name': 'lulu'}), {})
85 ------------------------------
86 {'__delitem__': <function __delitem__ at 0x029AECF0>, '__module__': '__main__', '__getitem__': <function __getitem__ at 0x029AEC70>, 'food': 'baozi', '__str__': <function __str__ at 0x029AEC30>, '__doc__': '\xe6\xad\xa4\xe7\xb1\xbb\xe6\x98\xaf\xe5\xbd\xa2\xe5\xae\xb9Dog\xe8\xbf\x99\xe4\xb8\xaa\xe7\xb1\xbb', '__dict__': <attribute '__dict__' of 'Dog' objects>, '__del__': <function __del__ at 0x029AEBB0>, '__setitem__': <function __setitem__ at 0x029AECB0>, '__call__': <function __call__ at 0x029AEBF0>, '__weakref__': <attribute '__weakref__' of 'Dog' objects>, 'eat': <function eat at 0x029AEB70>, '__init__': <function __init__ at 0x029AE9B0>}
87 {'name': 'lulu'}
88 ------------------------------
89 <obj:lulu>
90 ------------------------------
91 ('__setitem__:', 'age', 3)
92 ('__getitem__:', 'age')
93 None
94 ('__delitem__', 'age')

 

posted @ 2017-06-30 16:26  不知所以  阅读(108)  评论(0)    收藏  举报