metaclasside
# 在Python中,一切事物都是对象。 **** # class foo: # pass # obj=foo() # obj是foo的对象 # foo类是type的对象 # 只要写类,默认都继承object类 #类都是type类的对象 class myType(type): def __init__(self,*args,**kwargs): print("mytype") pass def __call__(self, *args, **kwargs): #这里的self是mytype的执行对象foo类 print("456") r=self.__new__() class foo(object,metaclass=myType): def __init__(self): pass def __new__(cls, *args, **kwargs): #__new__方法是真正建立对象的 return "对象" def fun(self): print("hello") # mytype obj=foo() #foo是myType对象,foo() 对象()是执行myType类的__call__方法 # 456 #obj # 真实是先建立的TYPE的__init__方法,再执行__call__方法,再执行__new__方法,最后才执行foo类的__init__方法
总结:
2、特殊成员
_init_ 类()自动执行,重要
_del_ 析构方法
_call_ 对象() 类()() 自动执行
_int_ int(对象)
_str_ str(),很重要
_add_
_dict_ # 将对象中封装的全部内容经过字典的形式返回,很重要code
obj3=foo("zhangsan",60) d=obj3.__dict__ print(d) # {'name': 'zhangsan', 'age': 60} print(foo.__dict__) #查看类的成员 # {'__module__': '__main__', '__init__': <function foo.__init__ at 0x000000BAD00FD158>, '__add__': <function foo.__add__ at 0x000000BAD00FD1E0>, '__dict__': <attribute '__dict__' of 'foo' objects>, '__weakref__': <attribute '__weakref__' of 'foo' objects>, '__doc__': None}
_getitem_ # 切片(slice类型)或者索引
_setitem_
_delitem_对象
_iter_继承
# 对象.__iter__() 的返回值: 迭代器 # for 循环,迭代器,next \# for 循环,可迭代对象,对象.__iter__(),迭代器,next \ # 一、执行li对象的类F类中的 __iter__方法,并获取其返回值 \ # 二、循环上一步中返回的对象
i=iter([11,22,33,44]) i.next() i.next() i.next() i.next() #i是迭代器 for item in i: print(iterm) #i是可迭代对象 ,执行对象的__iter__方法,获取 for item in i: print(item)
3、metaclass,类的祖宗
a. Python中一切事物都是对象
b.
class Foo:
pass
obj = Foo()
# obj是对象,Foo类
# Foo类也是一个对象,type的对象
c.
类都是type类的对象 type(..)
“对象”都是以类的对象 类()索引