类的特殊成员方法

 1 # 类的特殊成员方法
 2 import sys
 3 
 4 class Cat(object):
 5     '''这个类是描述喵这个对象的'''
 6     def __init__(self, name, age):
 7         self.name = name
 8         self.age = age
 9 
10     def __call__(self, *args, **kwargs):
11         print("run call", args, kwargs)
12 
13     # def __str__(self):
14     #     print("__str__ contents")
15 
16 print(Cat.__doc__)  #打印这个类的描述信息
17 
18 c = Cat(1, 2)
19 print(c.__module__)  #输出模块
20 print(c.__class__)  #输出类
21 
22 
23 # __init__  #构造方法:创建对象时触发
24 # __del__  #析构方法
25 
26 # __call__  #由对象后加()触发
27 c(1, 2, 3, name="sa")  #run call
28 Cat(1, 2)(1, 2, 3, name="sa")
29 
30 #__dict__  #查看类或者对象的所有成员
31 print(Cat.__dict__)  #以一个字典形式把类中的属性方法都打印出来
32 print(c.__dict__)  #通过实例调用值打印实例变量
33 
34 #__str__  #如果一个类中定义了__str__方法 那么打印对象时 默认输出该方法的返回值 否者返回的是一个内存地址
35 print(c)
36 
37 #__getitem__ __setitem__ delitem__   #把实例搞成一个字典
38 class Fooo(object):
39     def __init__(self):
40         self.data = {}
41 
42     def __getitem__(self, item):
43         print("getitem", item)
44         return self.data.get(item)
45 
46     def __setitem__(self, key, value):
47         print("setitem", key, value)
48         self.data[key] = value
49 
50     def __delitem__(self, key):
51         print("delitem", key)
52 
53 f = Fooo()
54 f["name"] = "嗷巴马"
55 print(f["name"])
56 del f["name"]
57 
58 # 类是由type实例化创建的
59 print(type(f))
60 print(type(Fooo))
61 #创建类的两种方式 普通 -> 特殊
62 def func(self):
63     print("hello world %s" %self.name)
64 def __init__(self, name, age):
65     self.name = name
66     self.age = age
67 Foo = type("Foo", (object,), {"talk":func, "__init__":__init__})  #key __init__ 不能乱写
68 ff =Foo('无图以对', 2)
69 # type第一个参数:类名
70 # type第二个参数:当前类的基类
71 # type第三个参数:类的成员 key->value
72 print(type(Foo))
73 print(ff)
74 ff.talk()
75 
76 #__new__ \ __metaclass__
77 class MyType(type):
78     def __init__(self, what, bases=None, dict=None):
79         super(MyType, self).__init__(what, bases, dict)
80     def __call__(self, *args, **kwargs):
81         obj = self.__new__(self,*args, **kwargs)
82         self.__init__(obj)
83 class Man(object):
84     __metaclass__ = MyType #原类:定义你的类如何被创建
85     def __init__(self, name, age):
86         print("__init__")
87         self.name = name
88         self.age = age
89     def __new__(cls, *args, **kwargs):
90         print("__new__")
91         return object.__new__(cls) #此处是把Man传进去了 相当于去继承父类的new方法 必须return
92 m = Man("Ass", 22)
93 print(m) # new先于init执行 new是用户来创建实例的 new 中不return对象 类就无法实例化
94         #call创建new  new创建init

 

posted @ 2017-07-03 15:33  Bird_getUpEarly  阅读(197)  评论(0编辑  收藏  举报