类的起源
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了类的起源相关的知识,希望对你有一定的参考价值。
```#
## 特殊方式创建类
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)
以上是关于类的起源的主要内容,如果未能解决你的问题,请参考以下文章