```#
## 特殊方式創建類
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)
類的起源
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.