python學習筆記1-元類__metaclass__,元類__metaclass_

來源:互聯網
上載者:User

python學習筆記1-元類__metaclass__,元類__metaclass_

type 其實就是元類,type 是python 背後建立所有對象的元類 python 中的類的建立規則:假設建立Foo 這個類
class Foo(Bar):  def __init__():    pass
 用途:元類的主要目的就是為了當建立類時能夠自動地改變類,元類的主要用途是建立API。一個典型的例子是Django ORM。它允許你像這樣定義:Flask sqlalchemy ORM 類的定義也是通過繼承一個被建立的類Base, 並且要注意sqlalchemy 中所有的表類必須繼承一個Base 對象,不然繼承後建立的Base的表將無法實現ORM映射; sqlalchemy 執行個體: 
from sqlalchemy.ext.declarative import declarative_baseBase = declarative_base()class HotWordType(Base):    # 表名稱    __tablename__ = 'hotWordType'    # id typeName    id = Column(Integer, primary_key=True)  # 主鍵    typeName = Column(String(20), nullable=False)  # 類型名    hotWord = relationship('HotWord', backref='hotWordType')
declarative_base 中的元類源碼:
The new base class will be given a metaclass that producesappropriate :class:`~sqlalchemy.schema.Table` objects and makesthe appropriate :func:`~sqlalchemy.orm.mapper` calls based on theinformation provided declaratively in the class and any subclassesof the class.class DeclarativeMeta(type):    def __init__(cls, classname, bases, dict_):        if '_decl_class_registry' not in cls.__dict__:            _as_declarative(cls, classname, cls.__dict__)        type.__init__(cls, classname, bases, dict_)    def __setattr__(cls, key, value):        _add_attribute(cls, key, value) 

 

     

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.