类的起源



```#
## 特殊方式创建类
def func(self):
    print("hello %s"%self.name)
def ccc(self,name,age):
    self.name=name
    self.age=age
#Foo是实例也是对象,type是类的类(类他爹,类是type实例化产生的)
Foo=type("Foo",(object,),{"talk":func,
                          "__init__":ccc})
f=Foo("alex","12")
f.talk()

class MyType(type):
     def __init__(self,*args,**kwargs):

          print("Mytype __init__",*args,**kwargs)

     def __call__(self, *args, **kwargs):
       print("Mytype __call__", *args, **kwargs)
       obj = self.__new__(self)
       print("obj ",obj,*args, **kwargs)
       print(self)
       self.__init__(obj,*args, **kwargs)
       return obj

     def __new__(cls, *args, **kwargs):
         print("Mytype __new__",*args,**kwargs)
         return type.__new__(cls, *args, **kwargs)

print('here...')
class Foo(object,metaclass=MyType):
     def __init__(self,name):
         self.name = name

         print("Foo __init__")

     def __new__(cls, *args, **kwargs): #__new__是用来创建实例的(先执行)
         print("Foo __new__",cls, *args, **kwargs)
         return object.__new__(cls) #继承父类里的__new__方法

obj= Foo("Alex")
print(obj.name)
# print("f",f)
# print("fname",f.name)

猜你喜欢

转载自blog.51cto.com/12992048/2296150