日韩无码专区无码一级三级片|91人人爱网站中日韩无码电影|厨房大战丰满熟妇|AV高清无码在线免费观看|另类AV日韩少妇熟女|中文日本大黄一级黄色片|色情在线视频免费|亚洲成人特黄a片|黄片wwwav色图欧美|欧亚乱色一区二区三区

RELATEED CONSULTING
相關(guān)咨詢
選擇下列產(chǎn)品馬上在線溝通
服務(wù)時(shí)間:8:30-17:00
你可能遇到了下面的問(wèn)題
關(guān)閉右側(cè)工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營(yíng)銷解決方案
創(chuàng)新互聯(lián)Python教程:Python中的元類是什么?如何快速掌握?

作為一個(gè)的程序單元,學(xué)習(xí)編程的人應(yīng)該都需要掌握。今天小編為大家?guī)?lái)元類的講解。


Python2創(chuàng)建類的時(shí)候,可以添加一個(gè)__metaclass__屬性:

class Foo(object):
   __metaclass__ = something...
   [...]


如果你這樣做,Python會(huì)使用元類來(lái)創(chuàng)建Foo這個(gè)類。Python會(huì)在類定義中尋找__metaclass__。如果找到它,Python會(huì)用它來(lái)創(chuàng)建對(duì)象類Foo。如果沒(méi)有找到它,Python將使用type來(lái)創(chuàng)建這個(gè)類。

在Python3中語(yǔ)法改變了一下:


class Simple1(object, metaclass=something...):
   [...]


本質(zhì)上是一樣的。拿一個(gè)元類例子分享一下:


class HelloMeta(type):
   def __new__(cls, name, bases, attrs):
       def __init__(cls, func):
           cls.func = func
       def hello(cls):
           print 'hello world'
       t = type.__new__(cls, name, bases, attrs)
       t.__init__ = __init__
       t.hello = hello
       return t
       class New_Hello(object):
   __metaclass__ = HelloMeta


New_Hello初始化需要添加一個(gè)參數(shù),并包含一個(gè)叫做hello的方法:


In : h = New_Hello(lambda x: x)
In : h.func(10), h.hello()
hello world
Out: (10, None)


PS: 這個(gè)例子只能運(yùn)行于Python2。


以上就是Python中元類的詳解。更多Python學(xué)習(xí)推薦:PyThon學(xué)習(xí)網(wǎng)教學(xué)中心。


文章標(biāo)題:創(chuàng)新互聯(lián)Python教程:Python中的元類是什么?如何快速掌握?
文章出自:http://m.5511xx.com/article/cccseed.html