python 'type' - dynamically creating a class

         As you may already know, in python, a class is also an object.

         If you haven't known this, then you can just imagine everything in python is an object until you figure things out.


        Then this deviates the question whose objects  the classes are?  The meta class. And the meta class is also in fact, an object of it self.  Now I'm

So happy i've succeeded complicating everything~~ Forget it.


         You may want to google more about the metaclass which you can get a very good detailed explanation from here: http://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python


         Also, you may go on reading my page simply describing how to use a metaclass 'type'. Yes, 'type', the little thing you often use in a commandline for checking the type

of everything is in fact the metaclass for all new classes.

 

         I'll illustrate things by some codes to save time for both of us.


        def hello(sHello):

print sHello


       def createCls(func):

return type('myClass',  (object), {'val1':1, 'val2':2, 'method':func})


       Done with it. Let's try to use it.

      

        tCls = createCts(hello)


      print  tCls.val1

      print tCls.val2

      tCls.method('hello world')


       You should see the result in your terminal.



       BYW, you can also put the whole class creating like this:

           def createCls(func):

 class myClass(object):

                          def __init__(self,  val1, val2):

self.val1 = val1

  self.val2 = val2

                         def method(hello):

print hello


       But this is far from as flexible and easy to use as using type.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值