Python type, isinstance, and metaclass applications

Source: Internet
Author: User

Python type, isinstance, and metaclass applications

In Python, you can use the built-in function type to view the object type. isinstance can view that an object is a class instance. Dynamic classes can be implemented through type and dynamic classes can be implemented through metaclass.

Type () and isinstance () determine the object type
import typesclass Hello():    def hello(self, name='World'):        print('hello %s' % name)h = Hello()type(h) == types.InstanceType   //Truetype(Hello)==types.ClassType    //Truetype(isinstance)==types.BuiltinFunctionType //Trueisinstance(h, Hello)        //Truelst = [1, 2, 3]isinstance(lst, (int, str, list))   //True

Type () can be used to obtain the object type. The type is defined in the types module.
Isinstance (object, class-or-type-or-tuple)-> bool determines that an object is an instance of a class or subclass.

Type () implements dynamic classes

Another function of type () is to dynamically create a type.

>>> def fn(self, name='world'):...     print('hello %s' % name)...>>> HH = type('Hello', (object,),dict(hello=fn))>>> h = HH()>>> h.hello()hello world

Three parameters of type:
1) class Name;
2) A set of inherited parent classes. Note that Python supports multiple inheritance. If there is only one parent class, do not forget the single-element method of tuple;
3) The method name of the class is bound to the function. Here we bind the function fn to the method name hello.

Metaclass
#! /Usr/bin/env python #-*-coding: UTF-8-*-'simple ORM using metaclass '_ author _ = 'Michael liao' class Field (object ): def _ init _ (self, name, column_type): self. name = name self. column_type = column_type def _ str _ (self): return '<% s: % s>' % (self. _ class __. _ name __, self. name) class StringField (Field): def _ init _ (self, name): super (StringField, self ). _ init _ (name, 'varchar (100) ') class Integer Field (Field): def _ init _ (self, name): super (IntegerField, self ). _ init _ (name, 'bigint') class ModelMetaclass (type): def _ new _ (cls, name, bases, attrs ): if name = 'model': return type. _ new _ (cls, name, bases, attrs) print ('found model: % s' % name) mappings = dict () for k, v in attrs. iteritems (): if isinstance (v, Field): print ('found mapping: % s ==> % s' % (k, v )) mappings [k] = v for k in mapping S. iterkeys (): attrs. pop (k) attrs ['_ ings _'] = mappings # Save the ing between attributes and columns. attrs ['_ table _'] = name # assume that the table name and class name are consistent. return type. _ new _ (cls, name, bases, attrs) class Model (dict): _ metaclass _ = ModelMetaclass def _ init _ (self, ** kw): super (Model, self ). _ init _ (** kw) def _ getattr _ (self, key): try: return self [key] counter t KeyError: raise AttributeError (r "'model' object has no attribute '% S'" % key) Def _ setattr _ (self, key, value): self [key] = value def save (self ): fields = [] params = [] args = [] for k, v in self. _ mappings __. iteritems (): fields. append (v. name) params. append ('? ') Args. append (getattr (self, k, None) SQL = 'insert into % s (% s) values (% s) '% (self. _ table __,','. join (fields ),','. join (params) print ('SQL: % s' % SQL) print ('args: % s' % str (ARGS) # testing code: class User (Model ): id = IntegerField ('uid') name = StringField ('username') email = StringField ('email ') password = StringField ('Password') u = User (id = 12345, name = 'Michael ', email = 'test @ orm.org', password = 'my-pwd') u. save ()

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.