本文适用于解释python2 类的起源
· 在python中,自定义的类由 type 类创建,即自定义类时type类的实例。
创建类的两种方式:
1、普通方式:
class Foo(object): def func(self): print 'hello alex'
2、特殊方式:
def func(self): print("hello %s"%self.name) def __init__(self,name,age): self.name = name self.age = age Foo = type('Foo',(object,),{'func':func,'__init__':__init__}) f = Foo("jack",22) f.func() #type第一个参数:类名 #type第二个参数:当前类的基类 #type第三个参数:类的成员
类的起源:
类中有一个属性 __metaclass__,其用来表示该类由 谁 来实例化创建,所以,我们可以为 __metaclass__ 设置一个type类的派生类,从而查看 类 创建的过程。

· __new__是用来创建实例的。
· 类的生成 调用 顺序依次是 __new__ --> __init__ --> __call__
posted on
浙公网安备 33010602011771号