1. 程式人生 > >14.12.4類的特殊成員4

14.12.4類的特殊成員4

Python metaclass

類的特殊成員

metaclass

# 在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__方法

總結:
二、特殊成員
_init_ 類()自動執行,重要
_del_ 析構方法
_call_ 對象() 類()() 自動執行
_int_ int(對象)
_str_ str(),很重要
_add_
_dict_ # 將對象中封裝的所有內容通過字典的形式返回,很重要

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 方法,對象=》可叠代對象

            # 對象.__iter__() 的返回值: 叠代器
            # for 循環,叠代器,next
           \# for 循環,可叠代對象,對象.__iter__(),叠代器,next
           \ # 1、執行li對象的類F類中的 __iter__方法,並獲取其返回值
           \ # 2、循環上一步中返回的對象
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)  

三、metaclass,類的祖宗
a. Python中一切事物都是對象
b.
class Foo:
pass
obj = Foo()
# obj是對象,Foo類
# Foo類也是一個對象,type的對象
c.
類都是type類的對象 type(..)
“對象”都是以類的對象 類()

14.12.4類的特殊成員4