1、getitem等:
# Author : XueFeng
class Foo(object):
def __init__(self):
self.data = {}
def __getitem__(self, key):
print("__getitem__", key)
self.data.get(key)
def __setitem__(self, key, value):
print("__setitem__", key, value)
self.data["key"] = value
def __delitem__(self, key):
print("__delitem__", key)
f = Foo()
a = f["name"] # 自动触发执行 __getitem__
f["name"] = "jim" # 自动触发执行 __setitem__
del f["name"]
2、__new__方法:
# Author : Xuefeng
# class Foo(object):
# def __init__(self, name):
# self.Name = name
#
# f = Foo("Jim")
# print(type(f))
# print(type(Foo)) # Foo类的类是type
#
# def func(self):
# print("Hello %s" % self.name)
# def __init__(self, name, age):
# self.name = name
# self.age = age
#
# Poo = type("Poo", (object,), {"talk": func,
# "__init__": __init__}) # 第一个参数:类名 第二个参数:基类 第三个参数:类的成员
# p = Poo("Tom", 18)
# p.talk()
# print(p.__dict__)
# print(type(Poo))
# 类默认是由type实例化产生的,type类中如何实现的创建类?类又是如何创建对象?
# 答:类中有一个属性__metaclass__, 其用来表示该类由谁来实例化创建,所以我们可以为
# __metaclass__设置一个type的派生类,从而查看类创建的过程
class Mytype(type):
def __init__(self, what, bases=None, dict=None):
super(Mytype,self).__init__(what, bases, dict)
def __call__(self, *args, **kwargs):
obj = self.__new__(self, *args, **kwargs) # 第二阶段,由Mytype的call方法调用Foo的new
self.__init__(obj, *args, **kwargs) # 第三阶段,执行Foo的init
class Foo(object):
__metaclass__ = Mytype # 第一阶段,执行Mytype的init
def __init__(self, name):
self.name = name
print("Foo ---init")
def __new__(cls, *args, **kwargs): # new 是用来创建实例的
print("Foo ---new")
# print(object.__new__(cls))
return object.__new__(cls) # 继承父类的new方法
f = Foo('Jim')
print(f.name)