DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
  • Refcardz
  • Trend Reports
  • Webinars
  • Zones
  • |
    • Agile
    • AI
    • Big Data
    • Cloud
    • Database
    • DevOps
    • Integration
    • IoT
    • Java
    • Microservices
    • Open Source
    • Performance
    • Security
    • Web Dev
DZone >

Declarative Metaclass

Snippets Manager user avatar by
Snippets Manager
·
Oct. 01, 05 · · Code Snippet
Like (0)
Save
Tweet
521 Views

Join the DZone community and get the full member experience.

Join For Free
Metaclass is like a black magic in python.
I wouldn't learn it if not necessary to read someone's code.
SqlObject uses it. So, if I want to port it to pys60 Dbms,
I need to learn metaclass.

Fortunately, this one is not too much to understand.

class DeclarativeMeta(type):
    def __new__(meta, class_name, bases, new_attrs):
        cls = type.__new__(meta, class_name, bases, new_attrs)
        if new_attrs.has_key('__classinit__'):
            cls.__classinit__ = staticmethod(cls.__classinit__.im_func)
        cls.__classinit__(cls, new_attrs)
        return cls

When you use it you do this

class YourClass(object):
    __metaclass__ = DeclarativeMeta
    # ... and other class variables
    def __classinit__(cls, new_attrs):
        # do whatever you want with the new class
        # ...
    def __init__(self):
        # do whatever you want with the new instance

You use this when you want a subclass to have some magic
done to it when it is first defined. What you say in
__classinit__ will get done to the new subclass, eg.
create more methods, properties, etc.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • JUnit 5 Tutorial: Nice and Easy [Video]
  • How to Determine if Microservices Architecture Is Right for Your Business?
  • How to Upload/Download a File To and From the Server
  • Fintech and AI: Ways Artificial Intelligence Is Used in Finance

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • MVB Program
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends:

DZone.com is powered by 

AnswerHub logo